Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从“导入模块”;“子目录”;在Python 3中_Python_Python 2.7_Python 3.x - Fatal编程技术网

从“导入模块”;“子目录”;在Python 3中

从“导入模块”;“子目录”;在Python 3中,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我有一个目录树,如下所示(使用可视化): 主目录中的\uuuu init\uuuuu.py包含命令import testsubdir,而testsubdir中的\uuuuu init\uuuuuuuuu.py包含import testsubsubdir。我注意到这在Python 2.7中有效,但在Python 3.5中不起作用: kurt@kurt-ThinkPad:~/Documents/Scratch/testdir$ python __init__.py kurt@kurt-ThinkPa

我有一个目录树,如下所示(使用可视化):

主目录中的
\uuuu init\uuuuu.py
包含命令
import testsubdir
,而
testsubdir
中的
\uuuuu init\uuuuuuuuu.py
包含
import testsubsubdir
。我注意到这在Python 2.7中有效,但在Python 3.5中不起作用:

kurt@kurt-ThinkPad:~/Documents/Scratch/testdir$ python __init__.py
kurt@kurt-ThinkPad:~/Documents/Scratch/testdir$ python3 __init__.py
Traceback (most recent call last):
  File "__init__.py", line 1, in <module>
    import testsubdir
  File "/home/kurt/Documents/Scratch/testdir/testsubdir/__init__.py", line 1, in <module>
    import testsubsubdir
ImportError: No module named 'testsubsubdir'
kurt@kurt-ThinkPad:~/Documents/Scratch/testdir$python\uuu init\uuuu.py
kurt@kurt-ThinkPad:~/Documents/Scratch/testdir$python3\uuu init\uuuu.py
回溯(最近一次呼叫最后一次):
文件“\uuuu init\uuuuu.py”,第1行,在
导入testsubdir
文件“/home/kurt/Documents/Scratch/testdir/testsubdir/_init__.py”,第1行,在
导入testsubsubdir
ImportError:没有名为“testsubsubdir”的模块
我正在将一些源代码从Python2“翻译”到Python3,其中包含一个类似于上面的import语句。在Python 3中实现这一点的最佳方法是什么?

建议使用相对导入:

在顶层
\uuuu init\uuuuuuuuuuupy

from . import testsubdir
from . import testsubsubdir
testsubdir/\uuuu init\uuuu.py
中:

from . import testsubdir
from . import testsubsubdir

这对你有用吗?我获取
ValueError:尝试在非包中对来自的行
进行相对导入。导入testsubdir
@KurtPeek我通过将顶层
\uuu init\uuuuuuuuuupy
放入一个包
testdir
并执行
import testdir
@KurtPeek来测试,如果您想直接将顶层
\uuuuuuuuu init\uuuuuuuuuuuuuuuuuuupy
馈送到python3,则将
import
语句作为
导入testsubdir