gpt4 book ai didi

python - 动态导入模块

转载 作者:行者123 更新时间:2023-11-30 23:31:39 25 4
gpt4 key购买 nike

如何在不重新启动程序并手动执行的情况下保留导入?

我已经尝试过这个:

class runProgram:
def cmdEval(self,data):
try:
return str(repr(eval(data)))
except Exception as e:
return e
def cmdImport(self,data):
try:
__import__(data)
return "Imported."
except:
return "Error to import"
def run(self):
while True:
command = input("Command: ")
command,data = command.split(" ",1)
if command == "ev": print(self.cmdEval(data))
elif command == "imp": print(self.cmdImport(data))

然后我做了以下事情:

>>> runProgram().run()
Command: imp time
Imported.
Command: ev time.time()
name 'time' is not defined

结果不起作用,正如我预期的那样,但他们是否可以在不保存数据的情况下动态导入?我的意思是我希望能够使用它,但我不希望在重新启动后使用它,我只是希望能够在那里使用它,以防我需要为该特定 session 导入某些内容例如,这将是所需的结果我想要,

imp time
ev time.time()
>1383535034.20894
>>> ================================ RESTART ================================
>>> time.time()
Traceback (most recent call last):
File "<pyshell#238>", line 1, in <module>
time.time()
NameError: name 'time' is not defined

这可能吗?

最佳答案

__import__返回导入的模块,并且不改变全局命名空间。

替换以下行:

__import__(data)

与:

globals()[data] = __import__(data)

关于python - 动态导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19761144/

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