Bash/Python 错误处理?

VDV*_*VDV 4 python bash

我正在尝试将包含错误处理的非常基本的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 退出状态,但显然情况并非如此?

  1. 我的代码没问题吗?
  2. 有没有办法强制 Python 先处理错误而不调用 Bash?
  3. 将 Python 程序(大概是正确编写的)作为 Bash 脚本运行时,是否还有其他严重的陷阱?

Jac*_*ijm 5

您使用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 中的 。

  • @Avinash Raj:如果在使用 Python2 时输入 `p` 而不是数字,则会出现此错误,但如果使用 Python3 则不会,因为 `input` 做了不同的事情。 (3认同)