一台机器上的Python未绑定本地错误,但另一台机器上没有

2024-04-19 21:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一台机器上得到python脚本中的“UnboundLocalError:localvariable's'referenced before assign”,但在另一台运行正常的机器上没有。这两台机器都在Windows7上,并使用Python2.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

Tags: intestself机器loginputifmatch
2条回答

也许正如@inspectorG4dget所说的,您在某个地方有一个不同的代码路径。下面是一个简单的例子,它可能导致您的错误

def f():
    if machine1:
        s = 1
    else
        S = 2
    print s

如果要显示代码,可能只需要几秒钟就可以找到

问题出在这条线上:

self.testToDiagDict[test][inputSentence].append(inputSentences[0])

在这个范围内没有inputSentence

因此代码可能在一台机器上工作,因为这if statement

if "INPUT_SENTENCE" in line:

计算结果为true,但如果不是,则得到错误。我不能建议一个修复方案,因为我不知道您的代码的其余部分是什么样子,也不知道您试图完成什么,但是我指出的很多内容应该允许您重新评估您的设计

相关问题 更多 >