2

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.

2
  • Have you tried using a symlink from my_package to my_other_package/my_other_module.py? Commented Jul 22, 2013 at 22:51
  • Have you tried adding a __init__.py to /path/to/foo as well? I don't think you can do this if foo is not a package in itself. Commented Jul 22, 2013 at 23:07

1 Answer 1

1

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.

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

1 Comment

Thanks. I have read that tampering with sys.path is not a good idea, but I guess this the best I could do..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.