我运行的是Python 2.5。

这是我的文件夹树:

ptdraft/
  nib.py
  simulations/
    life/
      life.py

(我在每个文件夹中都有__init__.py,为了可读性,这里省略了)

我如何从生命模块内导入nib模块?我希望不需要修改sys.path就可以做到。

注意:正在运行的主模块在ptdraft文件夹中。


当前回答

我发现下面的方法可以从脚本的父目录导入包。在这个例子中,我想从app.db包中导入env.py中的函数。

.
└── my_application
    └── alembic
        └── env.py
    └── app
        ├── __init__.py
        └── db
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

其他回答

如果将模块文件夹添加到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

在我看来,你并不真的需要导入父模块。让我们假设在nib.py中有func1()和data1,你需要在life.py中使用

nib.py

import simulations.life.life as life
def func1():
   pass
data1 = {}
life.share(func1, data1)

life.py

func1 = data1 = None

def share(*args):
   global func1, data1
   func1, data1 = args

现在您可以访问life.py中的func1和data。当然,在尝试使用它们之前,你必须小心地在life.py中填充它们,

你可以在“模块搜索路径”中使用OS依赖路径。路径。 因此,您可以轻松地添加如下父目录

import sys
sys.path.insert(0,'..')

如果要添加父-父目录,

sys.path.insert(0,'../..')

这在python2和python3中都适用。

二线最简解

import os, sys
sys.path.insert(0, os.getcwd()) 

如果父目录是你的工作目录,你想从子脚本调用另一个子模块。

您可以在任何脚本中从父目录导入所有子模块并执行

python child_module1/child_script.py

我有一个问题,我必须导入一个Flask应用程序,它有一个导入,也需要在单独的文件夹中导入文件。这部分使用了Remi的答案,但假设我们有一个像这样的存储库:

.
└── service
    └── misc
        └── categories.csv
    └── test
        └── app_test.py
    app.py
    pipeline.py

然后,在从app.py文件导入app对象之前,我们将目录向上更改一层,因此当我们导入app(它导入了pipeline.py)时,我们也可以读入其他文件,如csv文件。

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)

os.chdir('../')
from app import app

在导入Flask应用程序之后,你可以使用os.chdir('./test'),这样你的工作目录就不会被改变。