Python packages: relative imports

为君一笑 提交于 2019-12-19 08:28:02

问题


I'm working on a Python application consisting of a core and multiple independent modules using the core. I'm having difficulty setting up relative imports of packages.

app
  |- __init__.py
  |- core
        |- __init__.py
        |- corefile.py

  |- module1
        |- __init__.py
        |- main.py

The __init__.py files are empty. I'm running Python 2.7.1.

main.py
from .core import *

Running python main.py results in ValueError: Attempted relative import in non-package.

Similar questions: Ultimate answer to relative python imports, How to do relative imports in Python?, Relative imports in Python

Thanks for the help.


回答1:


In short, you can only use relative imports from packages that are, themselves, imported.

For example, if you had:

$ cat run.py
from app.module1 import main
main.main()
$ python run.py

Then you could use a relative import in app/module1/main.py (although it would need to be from ..core import foo, because core/ is one level above main.py).




回答2:


import sys
abs_filepath = '/home/n/Documents/IMPORTANT/deep_learning/drori_2018/    final_proj/Ryans_branch/StackGAN/'
# insert your absolute filepath above as abs_filepath = '/path/to/targ/dir'
sys.path.append(abs_filepath)

Please correct it if there are problems with doing the import this way

Other Answers:

Also please see here for a thorough answer about what's going on.



来源:https://stackoverflow.com/questions/10059002/python-packages-relative-imports

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