【问题标题】:python's execfile() variable scope issuepython的 execfile() 变量范围问题
【发布时间】:2016-01-14 01:34:37
【问题描述】:

我有一堆我从父 python 脚本调用的 python 脚本,但是我在使用我在父 python 脚本中调用的脚本的变量时遇到了麻烦。场景示例:

parent.py:

eventFileName = './0426_20141124T030101Z_NS3_T1outside-TEST-NS3.csv'
execfile('./parser.py')
print(experimentID) #I was hoping 0426 will be printed to screen but I am getting an error: global name 'experimentID' is not defined 

./parser.py:

fileNameOnly  = (eventFileName).split('/')[-1]
experimentID  = fileNameOnly.split('_')[0]

有什么建议吗? (以上只是我正在处理的案例的一个例子)

【问题讨论】:

  • 无法复制。你确定你正在执行你认为的文件吗?
  • @IgnacioVazquez-Abrams 抱歉,将 parent.py 中的变量名更正为 eventFileName。您应该能够运行这两个文件。但问题的关键是我无法在 parent.py 中使用 experimentID,而 parent.py 最初是在 parser.py 中填充的。

标签: python


【解决方案1】:

简而言之,您不能只在execfile() 中设置/修改局部变量——来自execfile() docs

注意默认局部变量的作用与下面对函数 locals() 的描述相同:不应尝试修改默认局部变量字典。如果您需要在函数 execfile() 返回后查看代码对局部变量的影响,请传递显式局部变量字典。 execfile() 不能可靠地用于修改函数的局部变量。

如需更全面的答案,请参阅this

如果你真的想设置 global 变量,你可以调用 execfile() 并使用 this answer 中描述的显式全局参数:

eventFileName = './0426_20141124T030101Z_NS3_T1outside-TEST-NS3.csv'
execfile('./b.py', globals())
print experimentID

如果您真的希望在parent.py 中设置一个本地 变量,那么您可以将本地字典显式传递给execfile()

eventFileName = './0426_20141124T030101Z_NS3_T1outside-TEST-NS3.csv'
local_dict = locals()
execfile('./b.py', globals(), local_dict)
print(local_dict["experimentID"])

【讨论】:

  • 完美。效果很好:-)
猜你喜欢
  • 2011-11-21
  • 2011-04-02
  • 2016-12-18
  • 2018-12-06
  • 1970-01-01
  • 2016-08-30
  • 2011-04-13
  • 2011-10-20
  • 2016-06-21
相关资源
最近更新 更多