如何在python中完成相对导入 [英] How to accomplish relative import in python

查看:143
本文介绍了如何在python中完成相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

stuff/
    __init__.py
    mylib.py
    Foo/
        __init__.py
        main.py
        foo/
            __init__.py
            script.py

script.py 想要导入 mylib.py

这只是一个例子,但实际上我只是想在父目录中进行模块的相对导入。我尝试了各种各样的事情并得到了这个错误......

This is just an example, but really I just want to do a relative import of a module in a parent directory. I've tried various things and get this error...

尝试相对导入超出toplevel包

我在某处读到程序启动的脚本不应该在包中,我尝试修改结构就像这样......

I read somewhere that the script from where the program starts shouldn't in the package, and I tried modifying the structure for that like so...

stuff/
    mylib.py
    foo.py // equivalent of main.py in above
    foo/
        __init__.py
        script.py

但得到同样的错误。

我怎样才能做到这一点?这甚至是一个合适的方法吗?

How can I accomplish this? Is this even an adequate approach?

编辑:在Python 2中

In Python 2

推荐答案

稍微摆弄它之后,我意识到如何设置它,为了特殊起见,我不会使用foo bar名称。我的项目目录设置为...

After fiddling with it a bit more, I realized how to set it up, and for the sake of specificity I won't use foo bar names. My project directory is set up as...

tools/
    core/
        object_editor/
            # files that need to use ntlib.py
            editor.py # see example at bottom
            __init__.py
        state_editor/
            # files that need to use ntlib.py
            __init__.py
        ntlib.py
        __init__.py # core is the top level package
    LICENSE
    state_editor.py # equivalent to main.py for the state editor
    object_editor.py # equivalent to main.py for the object editor

一行 object_editor.py 看起来像......

A line in object_editor.py looks like...

from core.object_editor import editor

editor.py 中的一行如下所示。 ..

A line in editor.py looks like...

from .. import ntlib

或者

from core import ntlib

关键是我在问题中给出的示例中,main脚本是从包中运行的。一旦我将其移出,创建了一个特定的包( core ),并移动了我希望编辑器共享的库( ntlib )进入那个包裹,一切都很笨拙。

The key is that in the example I gave in the question, the "main" script was being run from within the package. Once I moved it out, created a specific package (core), and moved the library I wanted the editors to share (ntlib) into that package, everything was hunky-dory.

这篇关于如何在python中完成相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆