gpt4 book ai didi

python - 我可以在 Python 2.7 中从基于 raw_input 的模块导入吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:48 25 4
gpt4 key购买 nike

在 Python 2.7 中是否可以获取用户输入并使用它来确定加载哪个模块?

我试过类似的方法:

userModule = raw_input("Which module to import? ")
from userModule import *

其中没有名为 userModule 的预先存在的模块...

目前返回:ImportError: No module named userModule

最佳答案

使用 importlib 模块和一些 globals() 技巧:

import importlib

userModule = raw_input("Which module to import? ")

mod = importlib.import_module('signal')
names = mod.__all__ if hasattr(mod, '__all__') else dir(mod)
g = globals()
for name in names:
g[name] = getattr(mod, name)
del g, name, names, mod, importlib

请注意,这并不是最简单直接的任务,您可能需要重新考虑这样做是否明智。

关于python - 我可以在 Python 2.7 中从基于 raw_input 的模块导入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13491384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com