谁能解释python的相对进口? [英] Can anyone explain python's relative imports?

查看:35
本文介绍了谁能解释python的相对进口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这辈子都无法让 python 的相对导入起作用.我创建了一个简单的例子来说明它不起作用的地方:

I can't for the life of me get python's relative imports to work. I have created a simple example of where it does not function:

目录结构为:

/__init__.py
/start.py
/parent.py
/sub/__init__.py
/sub/relative.py

/start.py 只包含:import sub.relative

/sub/relative.py 只包含 from .. import parent

所有其他文件都是空白的.

All other files are blank.

在命令行上执行以下内容时:

When executing the following on the command line:

$ cd /
$ python start.py

我明白了:

Traceback (most recent call last):
  File "start.py", line 1, in <module>
    import sub.relative
  File "/home/cvondrick/sandbox/sub/relative.py", line 1, in <module>
    from .. import parent
ValueError: Attempted relative import beyond toplevel package

我使用的是 Python 2.6.为什么会这样?我如何使这个沙箱示例工作?

I am using Python 2.6. Why is this the case? How do I make this sandbox example work?

推荐答案

您正在从包sub"导入.即使存在 __init__.pystart.py 本身也不在包中.

You are importing from package "sub". start.py is not itself in a package even if there is a __init__.py present.

您需要从 parent.py 上的一个目录启动您的程序:

You would need to start your program from one directory over parent.py:

./start.py

./pkg/__init__.py
./pkg/parent.py
./pkg/sub/__init__.py
./pkg/sub/relative.py

使用start.py:

import pkg.sub.relative

现在 pkg 是顶级包,您的相对导入应该可以工作了.

Now pkg is the top level package and your relative import should work.

如果你想坚持你当前的布局,你可以使用import parent.因为您使用 start.py 来启动解释器,所以 start.py 所在的目录在您的 python 路径中.parent.py 作为一个单独的模块存在.

If you want to stick with your current layout you can just use import parent. Because you use start.py to launch your interpreter, the directory where start.py is located is in your python path. parent.py lives there as a separate module.

您也可以安全地删除顶级 __init__.py,如果您不将任何内容导入到目录树更上方的脚本中.

You can also safely delete the top level __init__.py, if you don't import anything into a script further up the directory tree.

这篇关于谁能解释python的相对进口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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