问题
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