Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96264

Running Python on a module with relative imports from another directory

Say that under /path/to/foo I have package with a python module:

/path/to/foo:
           | my_package
                        | __init__.py
                        | my_module.py

           | my_other_package
                        | __init__.py
                        | my_other_module.py

The file my_module.py does a relative import of my_other_module.py as follows:

  from ..my_other_package import my_other_module

I understand that I can do the following from the shell:

> cd /path/to/foo
> python -m my_package.my_module

But what if I don't want to change my current directory? Is there any way to run my module from the shell without having to change PYTHONPATH?

I tried the following:

python -m /path/to/foo/my_package.my_module

but that didn't work. I got: Import by filename is not supported.

Upvotes: 2

Views: 1083

Answers (1)

Couchy
Couchy

Reputation: 763

Get the relative path:

base_path = os.path.abspath('../my_other_package/') #or any relative directory

append this to the system path (only temporary, will be deleted after execution): sys.path.append(base_path)

import the file you need in that path: import my_other_module.py

I believe it you may need a file named __init__.py (with nothing in it) if you wanted to import the file as import directory.file (correct me if I'm wrong).

This thread shows alternate approaches.

Upvotes: 1

Related Questions