简体   繁体   English

如何在 bash 脚本中运行 python 代码?

[英]How to run a python code inside a bash script?

I am able to run a python code inside a folder as我能够在文件夹中运行 python 代码

python mycode.py

without problems (on MacOS).没有问题(在 MacOS 上)。 However, I want to be able to run this code from anywhere else.但是,我希望能够从其他任何地方运行此代码。 So I define a small bash ( run_my_code ) script as follows所以我定义了一个小的 bash ( run_my_code ) 脚本如下

cd /path/to/my/folder
echo $PYTHONPATH
echo $PATH
pip list
pwd
python mycode.py

and run it as并将其运行为

run_my_code

which results in an ModuleNotFoundError .这会导致ModuleNotFoundError I checked and made sure that PYTHONPATH and PATH are the same in both environments.我检查并确保PYTHONPATHPATH在两种环境中都相同。 Even pip list list the same list of modules, even the one missing!!甚至pip list列出相同的模块列表,甚至缺少一个!

How can I fix this module/path error?如何修复此模块/路径错误?

I have answered my own question, but this only seems to be like a bad workaround.我已经回答了我自己的问题,但这似乎只是一个糟糕的解决方法。 There must be a better way to fix this!必须有更好的方法来解决这个问题!

I found a solution, but not sure it is a good solution:我找到了一个解决方案,但不确定它是否是一个好的解决方案:

  1. You add the line你添加行

    print(sys.path)

    to your code to print out all the path's used in that environment when you run the code as python mycode.py .当您将代码作为python mycode.py运行时,打印出该环境中使用的所有路径。

  2. You change your code to extend the paths at the very beginning of your code, ie like this您更改代码以在代码的最开头扩展路径,即像这样

    import sys sys.path.extend(<here the output from step 1>) import <all the other imports>
  3. Problem solved.问题解决了。

But is there a better way?但是有更好的方法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM