Bash / Python错误处理?

录像机

我正在尝试执行非常基本的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

这是来自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

据我了解,输入错误必须首先由Python处理,然后它将向Bash返回0退出状态,但是显然不是这样吗?

  1. 我的代码可以吗?
  2. 有没有一种方法可以强制Python在不引起Bash的情况下首先处理该错误?
  3. 当以Bash脚本运行Python程序(大概正确编写)时,是否还有其他严重的陷阱?
雅各布·弗利姆(Jacob Vlijm)

您使用Python 3(看“打印”)编写代码,但是shebang建议使用Python 2将shebang更改为

#!/usr/bin/env python3

并通过以下方式运行:

python3 /path/to/script.py

它将运行正常:)

解释:

正如Florian Diesch的评论所暗示的那样input(),Python 3已发生变化:

在Python 2中,input()尝试将输入用作Python表达式(如eval()),而在Python 3中尝试将输入input()替换为raw_input()Python 2。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章