简体   繁体   English

python:如何导入包?

[英]python : how to import packages?

This is my folder: 这是我的文件夹:

/Workspace
 somefiles.py
          /foopackage
           __init__.py
           foo1.py
           foo2.py

And the _ init _ .py contains _ init _ .py包含

from foo1 import foo1
from foo2 import foo2

And I want to import foopackage. 而且我想导入foopackage。 I have tried this: 我已经试过了:

>>>import sys
>>>sys.path.append('/home/username/Workspace')
>>>import foopackage
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/username/Workspace/foopackage/__init__.py", line 1, in <module>
    from foo1 import foo1
ImportError: No module named 'foo1'

I have tried sys.path.append('/home/username/Workspace/foopackage') instead and the thing fixed. 我试过了sys.path.append('/ home / username / Workspace / foopackage'),问题已经解决了。

I'm asking do I have to add every package directory to sys.path list to be able to import them? 我问我是否必须将每个软件包目录都添加到sys.path列表中才能导入它们?
or something else is wrong? 还是其他错误?

If you are using Python 3, you need to use explicit relative imports rather than implicit ones, which used to work in Python 2. Try updating foopackage 's __init__.py file to be: 如果您使用的是Python 3,则需要使用显式的相对导入而不是隐式的相对导入,后者在Python 2中可以正常工作。尝试将foopackage__init__.py文件更新为:

from .foo1 import foo1
from .foo2 import foo2

The leading . 领先. characters tell Python that foo1 and foo2 are sibling modules, rather than being top level modules that you're referring to absolutely. 字符告诉Python foo1foo2是同级模块,而不是您绝对指的顶级模块。 An alternative would be to use an absolute reference to them: 一种替代方法是对它们使用绝对引用:

from foopackage.foo1 import foo1
from foopackage.foo2 import foo2

But personally, I think that's a bit excessive. 但是我个人认为这有点过分。 It will also break if you change the package name at some point in the future (or move to be a subpackage of some other package). 如果将来在某个时候更改软件包名称(或成为其他软件包的子软件包),它也会中断。

See PEP 328 for more details on the changes to relative imports. 有关相对进口变更的更多详细信息,请参见PEP 328

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM