我在一台机器上的python脚本中得到“UnboundLocalError:在引用之前引用的局部变量”,但在脚本运行正常的另一台机器上没有。这两台机器都在Windows 7上并使用Python 2.7.3。有什么建议可能是这种行为的原因?谢谢。 这是导致错误的代码:
with open(self.temp_dir + test + ".log",'r') as log:
for line in log:
if "INPUT_SENTENCE" in line:
match = patternInput.match(line)
inputSentence = match.group(1).lower()
if inputSentence in self.testToDiagDict[test]:
continue
self.testToDiagDict[test][inputSentence] = []
if "STATS" in line:
if "Input Sentences" in line:
inputSentences = patternValue.findall(line)
self.testToDiagDict[test][inputSentence].append(inputSentences[0])
跟踪:
File "C:\X\Y\X\script.py", line 90, in extract_data
if "Input Sentences" in line:
UnboundLocalError: local variable 'inputSentence' referenced before assignment
答案 0 :(得分:0)
也许正如@ inspectorG4dget所说 - 你在某处有不同的代码路径。以下是可能导致错误的简单示例
def f():
if machine1:
s = 1
else
S = 2
print s
如果要显示代码,可能只需几秒钟即可找到
答案 1 :(得分:0)
问题在于这一行:
self.testToDiagDict[test][inputSentence].append(inputSentences[0])
该范围内没有inputSentence
因此,代码可能在一台计算机上运行,因为if statement
if "INPUT_SENTENCE" in line:
评估为true,但如果没有,则表示您收到该错误。我不能建议修复,因为我不知道你的代码的其余部分是什么样的,或者你想要完成什么,但我已经指出的应该允许你重新评估你的设计