NameError: глобальное имя 'interfaceName' не определено, даже если оно - PullRequest
0 голосов
/ 13 ноября 2018
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 голосов
/ 13 ноября 2018

С https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#variable-scope-and-lifetime

Переменная, которая определена внутри функции, является локальной для этого функция. Он доступен с точки, в которой он определен, до конец функции

Ваша переменная interfaceName определена только внутри области вашей функции putCardMon(). Он перестает существовать вне рамок функции. Следовательно, вы получаете ошибку.

Если вы хотите использовать переменную вне тела функции, рассмотрите возможность ее возврата и сохранения ее значения.

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)
    return interfaceName

# Later you can do this
interfaceName = putCardMon()
...