繁体   English   中英

从Python中的单独路径导入模块

[英]Importing modules from separate paths in Python

我正在尝试从单独的路径导入模块,但是返回的错误是“找不到模块”。 它从执行脚本的目录中导入模块,但不会更改目录并从该目录中导入。

print(os.getcwd())

当我运行它时,在抛出错误之前找不到模块,它将输出父目录,因此例如,我将使用test \\ import \\ modules

我将在\\ import \\中运行一个脚本,以从\\ import \\中导入test_0.pyd和从\\ modules中 导入 test_1.pyd(test.py和test_0位于\\ import \\中,而test_1位于\\ modules中 。此外,我还有尝试了相对导入,并且每个目录都包含init .py )。

import test_0 # this would work
from modules import test_1 # throws error that module isn't found

因此,我运行了print命令,它返回的是它试图从test \\导入,并且我尝试过更改目录,但是它将说工作目录在我打印时已更改,但仍然输出找不到模块。 非常感谢您的任何帮助,谢谢。

编辑 http://prntscr.com/6ch7fq-执行test.py http://prntscr.com/6ch80q-导入目录

当您从某个目录启动python时,该目录将添加到您的PYTHONPATH因此可以从该目录及其下导入模块,前提是您在每个目录中都有一个__init__.py ,其中包括从其运行python的顶层。 看这里:

~/Development/imports $ tree . ├── __init__.py ├── mod1 │ ├── __init__.py │ ├── a.py ├── mod2 │ ├── __init__.py │ ├── b.py ├── top.py

因此,当我们从~/Development/imports/启动python时,我们可以访问top mod1.amod2.b

~/Development/imports $ python
Python 2.7.8 (default, Nov  3 2014, 11:21:48)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import top
>>> import mod1.a
>>> import mod2.b
>>> import sys

但是,当我们从内部开始蟒蛇mod1 ,我们不允许到外面去的mod1topmod2

~/Development/imports/mod1 $ python
Python 2.7.8 (default, Nov  3 2014, 11:21:48)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import a
>>> from .. import top
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Attempted relative import in non-package
>>> from ..mod2 import b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Attempted relative import in non-package

from ..mod2 import b相对from ..mod2 import b只能在您从其开始的顶级模块下面的模块中工作,因为它们都隐式位于python路径中。

你无法逃避你,除非那个特定的路径添加到启动模块之外 PYTHONPATHsys.path

~/Development/imports/mod1 $ PYTHONPATH=../ python
Python 2.7.8 (default, Nov  3 2014, 11:21:48)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import a
>>> import top
>>> import top.mod2.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named mod2.b
>>> import sys
>>> sys.path.append('~/Development/imports/mod2/')
>>> from mod2 import b
>>>

因此,您需要确保所有目录中都有__init__.py文件。 您还需要确保从正确的位置(通常是顶层目录)启动python。 您无法在目录结构的一半以下启动python并期望回到顶部,或侧向另一个目录/模块。

在上述模块/目录中是否有__init__.py文件? 这是python将其视为包所必需的。

看看__init__.py的作用是什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM