简体   繁体   English

python的execfile()变量范围问题

[英]python's execfile() variable scope issue

I have bunch of python scripts I am calling from a parent python script but I am facing trouble using the variables of the scripts I called in parent python script. 我有许多从父python脚本调用的python脚本,但是使用在父python脚本中调用的脚本变量时遇到麻烦。 Example of the scenario: 方案示例:

parent.py : 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 : ./parser.py

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

any suggestions? 有什么建议么? (The above is just an example of a case I am working on) (以上只是我正在研究的案例的一个示例)

In brief, you can't just set/modify local variables in execfile() - from execfile() docs : 简而言之,您不能只在execfile()设置/修改局部变量-来自execfile()docs

Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. 注意:默认本地变量的行为与以下函数locals()的描述相同:不应尝试对默认本地变量字典进行修改。 Pass an explicit locals dictionary if you need to see effects of the code on locals after function execfile() returns. 如果需要在函数execfile()返回后查看代码对本地语言的影响,请传递一个明确的本地语言字典。 execfile() cannot be used reliably to modify a function's locals. execfile()无法可靠地用于修改函数的本地变量。

For a more comprehensive answer, see this . 有关更全面的答案,请参见this

If you really want to set global variable, you can call execfile() with an explicit globals argument as described in this answer : 如果您确实想设置全局变量,则可以使用此答案中所述的显式全局参数调用execfile()

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

If you really are looking to set a variable which is local in parent.py , then you can pass explicitly a locals dictionary to execfile() : 如果您确实想在parent.py设置本地变量,则可以将本地字典明确传递给execfile()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM