简体   繁体   English

从包中导入所有模块

[英]Import all modules from the package

I have a Python package with several modules. 我有一个包含几个模块的Python包。

What I can do: 我可以做什么:

It's possible to use all modules from the package in my program by modifying __init__.py of the package, by importing all modules in it: 通过修改包中的所有模块,可以通过修改包的__init__.py来使用程序包中的所有模块:

#__init__.py
import module1
import module2

Then I simply import package in my program and can access classes/functions in all the modules by their full name 然后我只需在我的程序中导入包,并可以通过其全名访问所有模块中的类/函数

#My program
import package
a = package.module1.A()

QUESTION: 题:

Is there any way to automate addition of imports to __init__.py so I don't need to specify them manually? 有没有办法自动添加导入到__init__.py所以我不需要手动指定它们?

This is another answer that might be closer to what you want. 这是另一个可能更接近您想要的答案。

In __init__.py you can add this to import all python files in the package. __init__.py您可以添加它以导入包中的所有python文件。

Note that it doesn't do packages.. not sure how. 请注意,它不做包..不知道如何。 And I'm using windows 我正在使用Windows

from os import listdir
from os.path import abspath, dirname, isfile, join
# get location of __init__.py
init_path = abspath(__file__)
# get folder name of __init__.py
init_dir = dirname(init_path)
# get all python files
py_files = [file_name.replace(".py", "") for file_name in listdir(init_dir) \
           if isfile(join(init_dir, file_name)) and ".py" in file_name and not ".pyc" in file_name]
# remove this __init__ file from the list
py_files.remove("__init__")

__all__ = py_files

The init file doesn't work like that.. I think you're thinking of something like this.. init文件不能像那样工作..我想你正在考虑这样的事情..

if you have the file structure: 如果你有文件结构:

my_program.py
/my_package
    __init__.py
    module1.py
    module2.py

in __init__.py you can write this line to edit the way import * works for my_package __init__.py您可以编写此行来编辑import *my_package工作方式

__all__ = ["module1", "module2"]

now in my_program.py you can do this: 现在在my_program.py你可以这样做:

from my_package import *
a = module1.A()

Hope that helps! 希望有所帮助! You can read more here: https://docs.python.org/2/tutorial/modules.html#importing-from-a-package 你可以在这里阅读更多内容: https//docs.python.org/2/tutorial/modules.html#importing-from-a-package

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

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