I have a python 2.7.15 project (I know, legacy reasons) living on my computer and I can run different files as a module from there:
cd /home/me/code/project
python -m path.to.module
This works fine. The problem is I am invoking these modules from another program living in another directory. Supposedly this will work if I set the PYTHONPATH.
export PYTHONPATH=/home/me/code/project
cd /home/me/code/controller
python -m path.to.module
However, this fails with:
No module named path.to.module
This fails directly on the command line, so it has nothing to do with me invoking it from another program.
How do I invoke this module from another directory, if PYTHONPATH does not succeed?
1 Answer 1
The issue with PYTHONPATH is it changes sys.path, which is how the python interpreter searches for modules when importing modules. This is different than calling python to run a script. Unfortunately, I do not know a pythonic solution to this. One solution is to run a bash script that changes these directories for you:
Create a bash script called runModule.sh
#!/bin/sh
python -m some_module
cd path/to/other_module
python -m other_module
Make it executable
chmod -x ./runModule.sh
Then run it
./runModule.sh
3 Comments
cding into that directory? This seems so bad, but I guess is in line with all the other python environment pain and gotchas. I'll find some other way, thanks!
python -mexpects the name of the module, not the path. If it's in yourPYTHONPATHyou should be able to run it withpython -m module.python -m pipis a good example of this.