NameError:即使全局名称“ interfaceName”也未定义

时间:2018-11-13 03:24:34

标签: python popen nameerror

def putCardMon():
    interfaceName = input(('Type an interface name to put in monitor mode: '))
    print(colored('[+] ', 'green') + 'Trying to put the interface ' + colored(interfaceName, 'yellow') + ' in monitor mode\n')
    call(["sudo ifconfig " + interfaceName + " down; sudo iwconfig " + interfaceName + " mode monitor; sudo ifconfig " + interfaceName + " up"], shell=True)
    interfaceMonCheck = Popen(["iwconfig " + interfaceName + " | grep Mode | cut -d ':' -f2 | cut -d ' ' -f1"], shell=True, stdout=PIPE, universal_newlines=True).communicate()[0].rstrip()
    sleep (1)

---//lots of code before the putCardMon is called//---

interfacesList = Popen("ifconfig -a | grep Link | cut -d ' ' -f1", shell=True, stdout=PIPE, universal_newlines=True).communicate()[0].rstrip()
print('The available interfaces are:\n' + interfacesList + '\n')
putCardMon()
print('Checking if ' + interfaceName + ' is really in monitor mode.')
if interfaceMonCheck == 'Managed':
    print('The interface ' + colored(interfaceName, "green") + ' is not in monitor mode! Check if you typed the interface name correctly or contact support.\n')
    putCardMon()
elif interfaceMonCheck == 'Monitor':
    print(colored('The interface ' + colored(interfaceName, "green") + ' is in monitor mode!'))
    pass
else:
    print(colored('There was an unexpected error. Contact support!\n', "red"))
    exit()

该脚本运行正常,该函数完成了工作,但随后进入检查部分时,一切都变得艰难了。

Traceback (most recent call last):
  File "script.py", line 76, in <module>
    print('Checking if ' + interfaceName + ' is really in monitor mode.')
NameError: name 'interfaceName' is not defined

如果已经为该字符串分配了一个函数并成功为其分配了一个值,为什么没有定义interfaceName?

我在堆栈溢出中搜索了相同的错误,但是所有线程都得到了回答,这是一个缩进错误,或者该函数在调用后已定义,在此情况并非如此。 我真的没有选择。我尝试了一切。

1 个答案:

答案 0 :(得分:0)

来自getColor(i){ if (i % 2 === 0 && i != 0){i = 'odd';} if (this.courses && (this.courses.length - 1 === i)) {i = 'last'} switch (i) { case i = 0 : return 'orange'; case i = 'odd' : return 'blue'; } return 'red'; }

  

在函数内部定义的变量是该函数的局部变量   功能。从定义点一直可以访问到   函数的结尾

您的变量https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#variable-scope-and-lifetime仅在函数interfaceName的范围内定义。它在功能范围之外不再存在。因此,您会收到错误消息。

如果要在函数主体外部使用变量,请考虑将其返回并保存其值。

putCardMon()