0

我有一个结构像这样的项目(减少了很多以给出要点)......

State_Editor/
    bin/
    state_editor/
        __init__.py
        main.py
        features/
            __init__.py
            # .py files
        io/
            __init__.py
            # .py files
        # etc.

你明白了。现在说例如foobar.pyfeatures做这个from state_editor.io.fileop import subInPath...... 显然State_Editor需要在路径中。

我已经阅读了有关 sys.path.append 和路径配置文件的信息,但我不确定如何完成我需要完成的任务,或者最 Pythonic 的方式是什么。

最大的问题是我不知道如何指定“一个目录向上”。显然这是..,但我不确定如何避免将其解释为字符串文字。例如,如果我这样做sys.path.append('../'),它将逐字附加../到路径中。

所以我的问题是,完成此任务的最“pythonic”方式是什么?

4

2 回答 2

3

在所述问题中,您需要 2 个前导点(包含导入的模块是 state_editor.features.foobar)。所以:

from ..io.fileop import SubInPath 

完整文档:

http://docs.python.org/reference/simple_stmts.html#the-import-statement

于 2010-09-27T01:36:48.980 回答
1

在足够近的 Python 版本中,@fseto 推荐的“相对导入”可能是最好的(可能from __future__ import absolute_import在模块顶部带有 a )。对于与各种 Python 版本兼容的解决方案,例如,

import sys
import os
sys.path.append(os.path.abspath(os.pardir))
于 2010-09-27T01:40:29.783 回答