在python中使用参数 - 值错误

时间:2017-05-21 03:48:20

标签: python

我是python编程的新手,我尝试了这段代码:

from sys import argv


script, first, second, third = argv
print "this script is called:" ,script

print "the first variable is called : " ,first

print "the second variable is called : ", second

print "the third variable is called : " ,third

我收到错误:

Traceback (most recent call last):
  File "/Users/richavarma/Documents/first.py", line 4, in <module>
    script, first, second, third = argv
ValueError: need more than 1 value to unpack

我的输出应该如下:

this script is called: abc.py
the first variable is called: first
the second variable is called : second
the third variable is called : third

1 个答案:

答案 0 :(得分:1)

简而言之,argv从命令行获取参数。如果在命令行中键入以下命令:

python test.py first second third

您将向python代码传递4个参数:test.py,first,second和third 你可以通过赋值来接受所有4个参数作为输入:

from sys import argv

(filename, arg1, arg2, arg3) = argv

在此之后,您可以将任何参数用作具有变量名称的字符串。