0

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!

5
  • 1
    Which module isn't found ? One from your own code or from a library ? Commented Jun 15, 2022 at 6:52
  • Try to enter a venv and pip install -r requirements.txt in your bash script. Make sure to run the Python code with the interpreter that's in the venv. Commented Jun 15, 2022 at 6:55
  • 1
    @viper a pip installable library (click) is not found. But it is listed in pip list! Commented Jun 15, 2022 at 7:01
  • have you seen stackoverflow.com/a/30379595/7384132? Commented Jun 15, 2022 at 7:03
  • I checked PYTHONPATH. They are the same! Commented Jun 15, 2022 at 7:23

1 Answer 1

0

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, i.e. 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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.