在终端中运行以下代码时:
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 中不起作用)。为什么它不在终端中运行?
谢谢
在 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'