[英]Python Import: import multiple modules in one file
I have many frequently used modules such as os, cv2, numpy,
... Every time I need to import them at the beginning of each python file. 我有很多常用的模块,例如
os, cv2, numpy,
。每次我需要在每个python文件的开头导入它们时。 Now I want to write the import
code into one file named all_import.py
, and for each python file only import all_import
to import all the modules I need. 现在,我想将
import
代码写入一个名为all_import.py
文件中,并且对于每个python文件,仅import all_import
即可导入我需要的所有模块。
Is that possible to do that? 有可能做到这一点吗?
Yes, this is possible (but really should not be done). 是的,这是可能的(但实际上不应该这样做)。 Just set up your files like so:
像这样设置文件:
b.py
b.py
import numpy
import scipy
a.py
py
from b import *
And then use whatever you imported in b.py
然后使用您在
b.py
导入的任何b.py
It is not recommended to do such thing but theoretically it is doable. 不建议这样做,但从理论上讲是可行的。
all_import.py
: all_import.py
:
import os
import cv2
import numpy
__all__ = ['os', 'cv2', 'numpy']
other_script.py
: other_script.py
:
import all_import as ai
# use `os`
ai.os.system('echo "Hello!"')
Comparing to @chrisz's answer, this one doesn't violate any PEP8 format. 与@chrisz的答案相比,此答案没有违反任何PEP8格式。
create a folder as python package 创建一个文件夹作为python包
my_fodler
inside it, create an __init__.py
file, where you add all your imports. 在其中创建一个
__init__.py
文件,在其中添加所有导入。
import os
import subprocess
go back to the same path as my_folder
and create your file, and there you call your package like: 返回与
my_folder
相同的路径并创建文件,然后在其中调用包,如下所示:
from my_folder import *
Here is how it would look like: 看起来像这样:
----|> my_folder
---- |>
my_folder
----|----> __init__.py
---- | ---->
__init__.py
----|> your_file.py
---- |>
your_file.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.