python 程序在 python shell 中的行为与终端不同
python program behaves differently in python shell vs terminal
我有一个简单的 Python 程序,可以询问是或否问题,然后我验证该输入。
如果我运行这个Pythonshell,它运行没问题。如果我输入无效字符,它会循环回到 while 的顶部。
但是,如果我 运行 在终端 window 中尝试输入无效字符,则会出现如下所示的错误。
endProgram = 0
while endProgram != 1:
userInput = input("Yes or No? ");
userInput = userInput.lower();
while userInput not in ['yes', 'no']:
print("Try again.")
break
endProgram = userInput == 'no'
我可以在交互式 shell 中清楚地看到您在 python 3.2.3(后台)中工作。但我无法从命令行(前台)看到 python 版本 运行。
在您的 raspberrypi 上,从 shell:
执行此命令
python --version
我期待在这里看到 python 2.x,因为 input()
的行为在 python 2 和 python 3 之间在某种程度上有所不同那将导致您所看到的行为。
您可能想添加一行
#!/usr/bin/env python3
到 .py
文件的顶部,然后 chmod +x
在上面。之后您应该可以直接执行它 (./guipy01.py
),并且会自动选择正确的 python 解释器。
看起来你的树莓派正在使用 Python 2; input
函数在那里执行 eval
。
Python 3 中的 input
等同于 Python 2 中的 raw_input
。(参见 PEP-3111)
理想情况下,您应该将 RPi 解释器更改为 Python 3。否则,您可以像这样使其与版本无关:
try:
input = raw_input
except NameError:
pass
我有一个简单的 Python 程序,可以询问是或否问题,然后我验证该输入。 如果我运行这个Pythonshell,它运行没问题。如果我输入无效字符,它会循环回到 while 的顶部。
但是,如果我 运行 在终端 window 中尝试输入无效字符,则会出现如下所示的错误。
endProgram = 0
while endProgram != 1:
userInput = input("Yes or No? ");
userInput = userInput.lower();
while userInput not in ['yes', 'no']:
print("Try again.")
break
endProgram = userInput == 'no'
我可以在交互式 shell 中清楚地看到您在 python 3.2.3(后台)中工作。但我无法从命令行(前台)看到 python 版本 运行。
在您的 raspberrypi 上,从 shell:
执行此命令python --version
我期待在这里看到 python 2.x,因为 input()
的行为在 python 2 和 python 3 之间在某种程度上有所不同那将导致您所看到的行为。
您可能想添加一行
#!/usr/bin/env python3
到 .py
文件的顶部,然后 chmod +x
在上面。之后您应该可以直接执行它 (./guipy01.py
),并且会自动选择正确的 python 解释器。
看起来你的树莓派正在使用 Python 2; input
函数在那里执行 eval
。
Python 3 中的 input
等同于 Python 2 中的 raw_input
。(参见 PEP-3111)
理想情况下,您应该将 RPi 解释器更改为 Python 3。否则,您可以像这样使其与版本无关:
try:
input = raw_input
except NameError:
pass