在"A.py“文件中,我编写了一个函数runPyFile,它简单地是
exec(open(file).read())但是现在当我在文件“B.py”中写时:
from A import *
runPyFile(myFile)然后这个myFile文件中定义的值在"B“文件中不可用。我怎样才能在"B“文件中使用它们?
发布于 2022-05-18 22:28:30
exec使用字典来保存执行代码中的全局和局部变量。传入globals()以使用它所在模块的全局。
exec(open(file).read(), globals())SSince --您需要能够从其他模块调用它,您可以编写runPyFile,以便它接受调用方传递的全局字典。然后调用方传递其globals()。
def runPyFile(file, globals):
exec(open(file).read(), globals)
runPyFile(myFile, globals())只需进行少量的堆栈检查,就可以获得调用方的全局值,而无需显式地传递它们。这是“魔术”,依赖于特定于CPython的细节,所以要谨慎使用。(如果调用方愿意,它仍然可以传递自己的全局。)
from inspect import currentframe
def runPyFile(file, globals=None):
if globals is None:
globals = currentframe().f_back.f_globals
exec(open(file).read(), globals)最后,只使用您自己的字典而不是模块的全局命名空间。这将执行代码的变量与任何模块的变量隔离开来,并允许您避免覆盖模块中的值,甚至类和函数。您可以创建一个dict子类,它允许您以属性的形式访问元素,以便更容易地访问这些变量。
from inspect import currentframe
class Variables(dict):
__getattr__ = dict.__getitem__
def runPyFile(file, globals=None):
if globals is None:
globals = Variables()
exec(open(file).read(), globals)
return globals
vars = runPyFile(myFile)
print(vars.a) # `a` defined in myFile
vars.func(...) # calls `func` defined in myFilehttps://stackoverflow.com/questions/72296642
复制相似问题