简体   繁体   中英

Python relative import to invoke script from random directory

I have the following directory structure:

test1/
test1/a.py
test1/test2/b.py

b.py needs to import a class in a.py. So I can add the following line to b.py before importing a.

sys.path.append(os.path.dirname(sys.argv[0]) + "/..")

This works and I can invoke b.py from any directory and it is able to import a. But this fails when I write a script in another directory to invoke this file using execfile().

I tried relative imports but I get a "Attempted Relative Import in Non-Package error"

from ..a import someclass as cls

I have __init__.py in both test1, test2

Does someone have an idea how to make it work? Is PYTHONPATH the way to go?

The problem is that execfile will evaluate the file you are calling as pure python code. Every relative import statement inside of b.py (and any package module imported by it) will have to remain true to your calling script.

One solution is to not use any relative import paths within the package. Make sure test1 package is on your PYTHONPATH as well.

b.py

from test1 import a

With test1 in your PYTHONPATH, the import of a should success in your execfile

>>> import sys
>>> sys.path.append('/path/to/parent/of_test1')
>>> execfile('/path/to/parent/of_test1/test1/test2/b.py')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM