我运行的是Python 2.5。
这是我的文件夹树:
ptdraft/
nib.py
simulations/
life/
life.py
(我在每个文件夹中都有__init__.py,为了可读性,这里省略了)
我如何从生命模块内导入nib模块?我希望不需要修改sys.path就可以做到。
注意:正在运行的主模块在ptdraft文件夹中。
我运行的是Python 2.5。
这是我的文件夹树:
ptdraft/
nib.py
simulations/
life/
life.py
(我在每个文件夹中都有__init__.py,为了可读性,这里省略了)
我如何从生命模块内导入nib模块?我希望不需要修改sys.path就可以做到。
注意:正在运行的主模块在ptdraft文件夹中。
当前回答
如果将模块文件夹添加到PYTHONPATH中失败,则可以修改sys. conf文件。Python解释器在你的程序中搜索要导入的模块的路径列表,Python文档说:
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations: the directory containing the input script (or the current directory). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). the installation-dependent default. After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended.
知道了这一点,你可以在程序中执行以下操作:
import sys
# Add the ptdraft folder path to the sys.path list
sys.path.append('/path/to/ptdraft/')
# Now you can import your module
from ptdraft import nib
# Or just
import ptdraft
其他回答
对我来说,访问父目录的最短和我最喜欢的联机程序是:
sys.path.append(os.path.dirname(os.getcwd()))
or:
sys.path.insert(1, os.path.dirname(os.getcwd()))
Os.getcwd()返回当前工作目录的名称,os.path.dirname(directory_name)返回传入目录的目录名称。
实际上,在我看来,Python项目架构应该是这样的:子目录中的任何模块都不会使用父目录中的任何模块。如果发生了这样的事情,就值得重新考虑项目树。
另一种方法是将父目录添加到PYTHONPATH系统环境变量。
虽然这是违反所有规则的,但我还是想提一下这种可能性:
您可以先将文件从父目录复制到子目录。接下来导入它,然后删除复制的文件:
例如,在life.py中:
import os
import shutil
shutil.copy('../nib.py', '.')
import nib
os.remove('nib.py')
# now you can use it just fine:
nib.foo()
当然,当nibs尝试使用相对导入/路径导入/读取其他文件时,可能会出现一些问题。
虽然原作者可能不再寻找解决方案,但为了完整,有一个简单的解决方案。它是像这样运行life.py模块:
cd ptdraft
python -m simulations.life.life
通过这种方式,您可以从nib.py导入任何东西,因为ptdraft目录在路径中。
上面提到的解决方案也很好。这个问题的另一个解决方案是
如果你想从顶级目录导入任何东西。然后,
from ...module_name import *
此外,如果您想从父目录导入任何模块。然后,
from ..module_name import *
此外,如果您想从父目录导入任何模块。然后,
from ...module_name.another_module import *
通过这种方式,如果您愿意,您可以导入任何特定的方法。
下面是一个更通用的解决方案,它将父目录包含到sys. conf中。路径(适用于我):
import os.path, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))