importing package and modules from another directory in python

浪尽此生 提交于 2020-01-16 20:03:46

问题


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


来源:https://stackoverflow.com/questions/28594000/importing-package-and-modules-from-another-directory-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!