NameError:name' ___'没有定义

时间:2014-04-20 17:15:48

标签: python variables input terminal

在终端中运行以下代码时:

import getpass
import sys
import telnetlib
import time

user = input("Please Enter Your Username: ")
password = input("Please Enter Your Password: ")
ip = input("Please Enter RPi IP Address: ")

bot = telnetlib.Telnet(ip)
bot.read_until("login: ")
bot.write(user + "\n")
bot.read_until("password: ")
bot.write(password + "\n")

我收到一条错误消息:

 Traceback (most recent call last):
   File "con.py", line 6, in <module>
     use = input("Please Enter Your Username: ")
   File "<string>", line 1, in <module>
 NameError: name 'pi' is not defined

P.S pi是被赋予变量user的东西。它运行在python shell中(直到它到达telnet部分,但它显然在shell中不起作用)。为什么它不会在终端上运行?

由于

1 个答案:

答案 0 :(得分:3)

在Python 2中,使用raw_input()而不是input()来从用户那里获取字符串输入。

input()尝试将输入计算为Python表达式;裸字符串在Python表达式中被视为变量名称,因此NameError。您可以输入"pi",但这不是一个出色的用户界面。

演示:

>>> input("Please Enter Your Username: ")
Please Enter Your Username: pi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'pi' is not defined
>>> raw_input("Please Enter Your Username: ")
Please Enter Your Username: pi
'pi'