蟒蛇。 NameError:未定义全局名称(没有类的函数)

时间:2017-02-16 13:15:32

标签: python function runtime-error

大家。

我的Python脚本有问题。这是一个问题代码(有" print"行只用于检查变量的值):

def checkForHittingLevel(name, curValue, checkLine):
 match = bool(False)
 if checkLine is None:
  return match
 for parametersForCheck in checkLine.split(';'):
  if name in parametersForCheck:
   actionWithLevel = parametersForCheck.replace(name,'')
   # Just to check that it's not empty or there is any problem:
   print actionWithLevel[0]
   print type(actionWithLevel)
   if actionWithLevel[0] == '>':
    match = True if curValue > actionWithLevel[1:] else False
    break
   elif actionWithLevel[0] == '<':
    match = True if curValue < actionWithLevel[1:] else False
    break
   elif actionWithLevel[0] == '=':
    match = True if curValue == actionWithLevel[1:] else False
    break
   elif actionWithLevel[0] == '!':
    match = True if curValue != actionWithLevel[1:] else False
    break
   else:
    match = False
    break
 return match

incArgs.add_argument('-c', '--critical-list', type=str, dest='criticals',
 help='List of critical values for checking data')
inpValue = incArgs.parse_args()
[... some code here ...]
for checkLine in dNetCoreStatsOutData.splitlines():
 checkStatName = str(checkLine.split()[0])
  checkStatValue = int(checkLine.split()[1])
  for checkPrevDataLine in oldData.splitlines():
   if checkStatName in checkPrevDataLine:
    prevValue = int(checkPrevDataLine.split()[1])
    diffValue = checkStatValue - prevValue
    if checkForHititngLevel(checkStatName, diffValue, inpValue.criticals):
     ... code here ...

如果我试图运行脚本,我会收到此输出:

>
<type 'str'>
Traceback (most recent call last):
  File "test.py", line ###, in <module>
    if checkForHitingLevel(some_name, 20, 'some_name>10'):
  File "test.py", line ###, in checkForHittingLevel
    if actionWithlevel[0] == '>':
NameError: global name 'actionWithlevel' is not defined

如果&#34; print&#34;使用的命令然后处理变量没有问题。但是,当我试图从字符串中获取特定字符时,我会收到错误。

我无法理解为什么会这样。如果它是Python的正常行为,那么我如何从行中获取字符(例如通过附加变量)?我知道的唯一方法是使用&#34; []&#34;。

PS 如果我尝试的话没有区别:

CheckResault = checkForHittingLevel(some_name, 20, 'some_name>10;name_2<10')

更新:已编辑的代码,因为某些变量名称存在问题。 Screenshot

UPDATE2:在我的第一个例子中,我只使用了函数的一部分以及如何调用它。我自己检查了这个例子并且它有效。但在完整代码中,它并没有。所以我在上面的信息中添加了调用此函数的代码部分。

2 个答案:

答案 0 :(得分:0)

您可以在开始时定义actionWithLevel。 然后你继续比较你从未定义的actionWithlevel ..这是一个不同的变量还是只是一个错字?你使用较低的&#34; l&#34;而不是资本&#34; L&#34; 。如果你确实想要与actionWithlevel进行比较(使用较低的&#34; l&#34;),你必须先定义它。

答案 1 :(得分:0)

好的,我确实找到了问题的根源。传递给函数的变量之一是在定义函数后定义的。此变量由argparse创建(变量名称为inpValue.criticals)。 当我在argparse之前使用def checkForHititngLevel移动行时,脚本停止显示错误。 我不知道它为什么会出现这种行为,因为函数中的print命令可以毫无问题地使用这个变量。