简体   繁体   中英

How to run a python code inside a bash script?

I am able to run a python code inside a folder as

python mycode.py

without problems (on 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

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 . I checked and made sure that PYTHONPATH and PATH are the same in both environments. Even pip list list the same list of modules, even the one missing!!

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 .

  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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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