簡體   English   中英

python的execfile()變量范圍問題

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

我有許多從父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]

有什么建議么? (以上只是我正在研究的案例的一個示例)

簡而言之,您不能只在execfile()設置/修改局部變量-來自execfile()docs

注意:默認本地變量的行為與以下函數locals()的描述相同:不應嘗試對默認本地變量字典進行修改。 如果需要在函數execfile()返回后查看代碼對本地語言的影響,請傳遞一個明確的本地語言字典。 execfile()無法可靠地用於修改函數的本地變量。

有關更全面的答案,請參見this

如果您確實想設置全局變量,則可以使用此答案中所述的顯式全局參數調用execfile()

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"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM