我搜索了这个错误,但我找不到答案。简单的计算程序:
import sys
from sys import argv
first = int(sys.argv[1])
operation = sys.argv[2]
second = int(sys.argv[3])
if operation == '+':
total = first + second
if operation == '-':
total = first - second
if operation == '*':
total = first * second
if operation == '/':
total = first / second
print "%d %s %d = %d" % (first, operation, second, total)
当我输入时:python first.py 2 / 2
我输出正确,与-
和+
相同,但当我输入python first.py 2 * 2
时,我得到:
Traceback (most recent call last):
File "first.py", line 7, in <module>
second = int(sys.argv[3])
ValueError: invalid literal for int() with base 10: 'first.py'`
答案 0 :(得分:3)
*
是 shell元字符,意思是:列出当前目录中的所有文件。
因此,sys.argv
未设置为['first.py', '2', '*', '2']
,而是设置为['first.py', '2', 'some-filename.txt', 'first.py', 'another-filename.py', '2']
或类似,因为shell首先将*
扩展为所有文件名,然后用这些名称称为Python。
逃离shell中的*
:
python first.py 2 \* 2