len(sys.argv)中的语法错误

时间:2016-06-16 18:43:03

标签: python

Python解释器在代码下运行时出现语法错误:

import sys

if len(sys.argv) == 3:
  a=sys.argv[1]
  b=sys.argv[2]
  sum=int(a) + int(b)
  print "The sum is: ", sum
elif len(sys.argv) != 3:
  print "Only two arguments allowed !"
else:
  print "Please enter two numbers as argument with the script. Try again !"

错误:

luckee@zarvis:~/python$ ./sumtwo.py 5 10
./sumtwo.py: line 3: syntax error near unexpected token `sys.argv'
./sumtwo.py: line 3: `if len(sys.argv) == 3:'

1 个答案:

答案 0 :(得分:3)

您的文件由shell解释,而不是Python解释器。在运行时尝试指定二进制文件:

luckee@zarvis:~/python$ python sumtwo.py 5 10

或者,您可以添加shebang作为脚本的第一行。

#!/usr/bin/python
import sys

if len(sys.argv) == 3:
  a=sys.argv[1]
  b=sys.argv[2]
  sum=int(a) + int(b)
  print "The sum is: ", sum
elif len(sys.argv) != 3:
  print "Only two arguments allowed !"
else:
  print "Please enter two numbers as argument with the script. Try again !"