importing package and modules from another directo

2019-09-03 02:05发布

问题:

I have a bunch of python scripts in the path

/home/yotam/Applications/pyFoo

one of them is __init__.py which, to my understanding, turns the pyFoo folder into a package. The folder also has a src subfolder, which stores an __init__.py file of its own, as well as some other helpful scripts.

I want to import one of the files (modules?), called Bar.py, that uses scripts from /home/yotam/Applications/pyFoo/src. If I try to load it from the python interpreter, while in the folder ''/home/yotam/Applications'' using

>>> from pyFoo import Bar as B

everything is fine. If, however I want to run it from other folders, e.g. my home directory, I get the error

ValueError: Attempted relative import in non-package

How can I import Bar.py from anyplace on my machine?

回答1:

Just add the directory to your sys.path:

import sys
sys.path.append( '/path/to/libs' )

import my_lib_in_another_dir