3

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?

martineau
124k29 gold badges181 silver badges319 bronze badges
asked Sep 14, 2019 at 1:07
2
  • 1
    python -m expects the name of the module, not the path. If it's in your PYTHONPATH you should be able to run it with python -m module. python -m pip is a good example of this. Commented Jun 8, 2020 at 11:27
  • 3
    @prismofeverything What workaround did you find? Commented Sep 23, 2020 at 6:23

1 Answer 1

3

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
answered Sep 14, 2019 at 3:02
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Ryan, thanks for the response! So you are saying that there is no way to run a module from another directory, without in some way 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!
The issue here is that the path variables that python uses to search are from within a python instance. You are calling a module on the command line from another directory. I may not understand your problem, but you could also build a python script that imports this module and change the sys.path variable within that python script to location of the module.
Got it, that makes sense! I found a workaround, thanks for the insight.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.