我正在尝试将包含错误处理的非常基本的Python代码作为Bash脚本执行,但是虽然代码在 Python 中似乎运行正常,但在 Bash 下执行时代码会产生问题。
#!/usr/bin/python
x = input('Enter your number: ')
try:
x = float(x)
print('Your number multiplied by 2 is: ', x*2)
except ValueError:
print('not a valid choice')
x == 0
Run Code Online (Sandbox Code Playgroud)
这是来自 Bash 的错误报告:
Enter your number: -p Traceback (most recent call last):
File "cycle.py", line 3, in <module>
x=input('Enter your number: ')
File "<string>", line 1, in <module>
NameError: name 'p' is not defined
Run Code Online (Sandbox Code Playgroud)
据我了解,输入错误必须首先由 Python 处理,然后它会向 Bash 返回 0 退出状态,但显然情况并非如此?
您使用Python 3编写代码(查看“打印”),但 shebang 建议使用Python 2。将shebang更改为
#!/usr/bin/env python3
Run Code Online (Sandbox Code Playgroud)
并通过以下方式运行它:
python3 /path/to/script.py
Run Code Online (Sandbox Code Playgroud)
它会运行良好:)
解释:
正如 Florian Diesch 的评论所暗示的那样,input()在 Python 3 中发生了变化:
在 Python 2 中,input()尝试将输入用作 Python 表达式(如eval()),而在 Python 3 中,则input()替换了raw_input()Python 2 中的 。