importing a package from a subdir or relative path

落花浮王杯 提交于 2020-01-03 21:05:14

问题


Here's my directory setup:

mydir
├── script1.py
└── shared
    ├── otherstuff
    ├── script2.py
    └── pkg
        ├── box.py
        └── __init__.py

script2.py starts with

import pkg 

and it works great. When I include the same line in script1.py, I get:

Traceback (most recent call last):
  File "script1.py", line 1, in <module>
    import pkg

Is there any good way to get syntax that simple to work in script1.py? I have been reading about PYTHONPATH and sys.path for the past hour, but I'm trying to make some basic functions available to my repo, and I can't believe that it will require modifying PYTHONPATH everytime I want to run a script.

What am I missing here? What's the best way to get pkg into script1.py?


回答1:


You have to do:

from shared import pkg

Also, your shared directory should have an __init__.py file




回答2:


I tested in python 3.x , You can do either -

import shared.pkg

or

from shared import pkg



回答3:


If you don't want to create the __init__.py file in shared and using import shared.pkg, you can work around this by doing:

import sys
sys.path.insert(0, 'shared')

import pkg


来源:https://stackoverflow.com/questions/31019492/importing-a-package-from-a-subdir-or-relative-path

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