这个问题是在python 2.7和相对导入的上下文中。我已经经历了相关的问题,但仍然不适合我。我不知道我在这里错过了什么?从兄弟目录导入的问题
以下是我的目录层次结构
.
|-> wrapper.py
|-> __init__.py
|-> util
| |-> hello.py
| |-> __init__.py
|-> src
| |-> wrapper.py
| |-> __init__.py
所有__init__.py都是空白文件只能以“视该目录为一个包”
以下是./util/hello.py如何读取。这有它自己的主要功能,可以自行运行。
#!/usr/bin/python
# This is hello.py.
import sys
# Define a main() function that prints a little greeting.
def main():
print "Hello World!!!"
# Standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
以下是./wrapper.py的内容。这也有它自己的主要功能,并使用./util/hello.py来实现其目标。
#!/usr/bin/python
# This is wrapper.py.
import sys
from util import hello
# Define a main() function that prints a little greeting.
def main():
hello.main() # This prints "Hello World!!!"
# Standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
以下是./src/wrapper.py如何读取。
#!/usr/bin/python
# This is wrapper.py.
import sys
from ..util import hello
# Define a main() function that prints a little greeting.
def main():
hello.main() # This prints "Hello World!!!"
# Standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
正如你看到的,这是最小的变化./wrapper.py的几乎一模一样的副本,使其运行(进口变化)。所有__init__.py也存在。但是,任何尝试运行它都会导致以下错误。
Traceback (most recent call last):
File "wrapper.py", line 8, in <module>
from ..util import hello
ValueError: Attempted relative import in non-package
但是,如果我输入hello.py如下原理:
import os
sys.path.append(os.path.abspath("../util/"))
import hello
两个问题:
Q1。我做错了什么或缺少我的注意力? Q2302。我怎样才能编码./src/__init__.py这样只需要“import hello”在./src/wrapper.py中工作?
你是如何运行的'/ wrapper.py'?相关 - https://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py –
有很多现有的答案,解决Q1,简单搜索“尝试在非包装中进行相对导入”。我无法回答Q2,因为问题导致了错误的方向。你可以运行'python -m src.wrapper',然后同样''hello import hello''在'src/wrapper.py'中运行。我认为避免从一般顶级以外的地方进口相对明智的做法是明智的! – mhoff
@AshishNitinPatil:以“python wrapper.py”的形式在“./src”中运行。 –