简体   繁体   English

是否可以从 python 3.8 中的不同目录导入 package 中的所有模块?

[英]Is it possible to import all modules within a package from a a different directory in python 3.8?

I am using Python 3.8.我正在使用 Python 3.8。 I have a directory structure like this:我有一个这样的目录结构:

├── package
│   ├── __init__.py
│   └── test2.py
└── test.py

Contents of test2:测试2的内容:

def x():
   print(999)

Contents of __init__.py: __init__.py 的内容:

from test2 import *

Contens of test.py: test.py 的内容:

import package
package.x()

Running test.py gives the following error:运行 test.py 会出现以下错误:

  from test2 import *
ModuleNotFoundError: No module named 'test2'

I want test.py to work as expected.我希望 test.py 按预期工作。 Please help.请帮忙。

As the @hjpotter92 said, the problem is in the __init__.py file because the importation should be:正如@hjpotter92 所说,问题出在__init__.py文件中,因为导入应该是:

from .test2 import *

And then to use the functions inside test2.py in test.py you just need something like this:然后要在test.py中使用test2.py中的函数,你只需要这样的东西:

import package
package.x()

Here you can find more information about this topic and some advices.在这里您可以找到有关此主题的更多信息和一些建议。

EDIT :编辑

The main reason why you have to import using from.test2 import * and not from test2 import * is because test2 is inside what Python calls a package (you called the directory with the same name) and it's supposed to use outside the same package(in test.py ), otherwise you wouldn't need to use .您必须使用from.test2 import *而不是from test2 import *的主要原因是因为test2在 Python 称为package的内部(您调用了同名的目录)并且它应该在同一个包之外使用(在test.py中),否则你不需要使用. to import it.导入它。

For instance, if you have a structure like this:例如,如果您有这样的结构:

├── package
│   ├── __init__.py
│   └── test2.py
|   └── test3.py
└── test.py

In test3.py you can do: from test2 import x because is in the same package (named package)test3.py你可以这样做: from test2 import x因为是在同一个package (命名包)

. represents to the package where the module is in, for example, if you wanna import in test.py without using __init__.py you should do this: from package.test2 import *代表模块所在的 package,例如,如果你想在test.py中导入而不使用__init__.py你应该这样做: from package.test2 import *

Hope this can help you:)希望这可以帮到你:)

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

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