prismofeverything
prismofeverything

Reputation: 9049

How to run a module from another directory?

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?

Upvotes: 3

Views: 2572

Answers (1)

Ryan
Ryan

Reputation: 133

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

Upvotes: 3

Related Questions