【问题标题】:Use exec to execute a file inside a function with globals()使用 exec 在带有 globals() 的函数内执行文件
【发布时间】:2017-12-06 20:35:07
【问题描述】:

我需要在 python shell 中执行一个文件。

我可以

exec(open('Test.py').read())

但我需要从函数内部调用它。

“Test.py”将设置变量C=10

所以,

#x.py
def load(file):
    exec(open(file).read(),globals())

>>> import x
>>> x.load('Test.py')
>>> C
>>> NameError: name 'C' is not defined

我已经传入了全局变量,但我仍然无法从 exec 访问变量。 参考资料:

In Python, why doesn't an import in an exec in a function work?

How to execute a file within the python interpreter?

【问题讨论】:

  • execfile("filepath")
  • 因为你我不能重现这个...
  • 提一下Python3.6会很有帮助。 'execfile' 不起作用

标签: python execfile


【解决方案1】:

所以这是一种方法

#x.py
def load(file):
    exec(open(file).read())
    return locals()

>>> import x
>>> var = x.load('Test.py')
>>> locals().update(var)
>>> C
>>> 10

希望对你有帮助

【讨论】:

  • 有没有办法让任何变量不关联“var”。直接访问C
  • 如果 x 在不同的目录中,你将如何访问?
  • 这不是破坏 x.py 的目的吗?不是应该从不同的目录调用文件吗?
  • 我想要一条可以在 shell 中执行的指令。可能吗?
【解决方案2】:

改用import

from Test import C
print C

编辑:

如果Test.py在不同的目录,你必须修改sys.path

import sys.path
sys.path.insert(0, "path_to_directory")

from Test import C
print C

【讨论】:

  • 如果我的测试位于不同的目录中,我该怎么办? (除了路径追加)
猜你喜欢
  • 1970-01-01
  • 2020-02-13
  • 2023-03-26
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多