如何导入所有可能不存在的模块和传递模块?
抱歉,如果标题令人困惑(如果您认为可以更好地解释它,请随时编辑)。
我想导入所有名为AH的模块(单独的Python脚本),但是对于它们是否存在的不确定性存在不确定性。如果它们不存在,我只想忽略它们,如果他们这样做。
我已经解决了一种方法,但是它很长,似乎是不必要的,而且我觉得必须有一种更好的方法来做到这一点。这是我的代码:
try:
from scripts import A
except:
pass
try:
from scripts import B
except:
pass
try:
from scripts import C
except:
pass
try:
from scripts import D
except:
pass
try:
from scripts import E
except:
pass
try:
from scripts import F
except:
pass
try:
from scripts import G
except:
pass
try:
from scripts import H
except:
pass
我该如何整理?
Sorry if the title's confusing (feel free to edit if you think you can explain it better).
I want to import all modules (seperate python scripts) named A-H, but there is uncertainty about whether they will exist or not. I want to just ignore them if they don't exist and import them if they do.
I have worked out a way, but it's long and seems unnecessary, and I feel like there must be a better way to do it. Here's my code:
try:
from scripts import A
except:
pass
try:
from scripts import B
except:
pass
try:
from scripts import C
except:
pass
try:
from scripts import D
except:
pass
try:
from scripts import E
except:
pass
try:
from scripts import F
except:
pass
try:
from scripts import G
except:
pass
try:
from scripts import H
except:
pass
How can I tidy this up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
方法1:
不是最好的做法,但是您可以尝试以下操作:
请注意,这会导入所有内容,因此有可能实质上污染您的名称空间。
方法2:
Method 1:
Not the best practice, but you can try this:
Note that this imports everything, and thus has a potential to substantially pollute your name space.
Method 2:
在我看来,您的要求本身在没有任何上下文的情况下有点混乱。
无论如何,后续代码似乎都需要一种处理丢失的模块的方法 - 我猜想有一个目的,并且将在某个时候使用。
要导入脚本中的“所有”现有模块,只需做:
On my mind, your request itself is a little bit confusing without any context.
In any case it seems that the follow up code will need a way to deal with the missing modules - I guess the have a purpose and are going to be used at some point.
To import "all" existing modules within scripts, just do:
动态导入:
您也可能需要将模块保存到变量上,以便您可以使用它做点什么
请注意,如果您这样做:
您需要定义
__ INT __。py
文件本身需要要导入所有存在的模块,因为import *
仅导入Python文件的内容,而不是目录的内容,以动态加载模块的全部目的。import dynamically:
also you may want to save the module to a variable so you can do something with it
note that if you do this:
you will need to define an
__init__.py
file which in itself will need to import all the modules which are present, asimport *
only imports the contents of python files, not the contents of directories, defeating the whole purpose of loading the modules dynamically.