我是python的新手,我只是在阅读练习不同的东西而且我想弄清楚为什么argv不能为我工作
from sys import argv
script, bike, car, bus = argv
print ("The script is called:"), script
print ("The first variable is:"), bike
print ("The second variable is "), car
print ("Your third variable is : "),bus
我收到一个需要超过1个值的错误才能解压缩
Traceback (most recent call last):
File "ex13.py", line 6, in <module>
script, bike, car, bus = argv
ValueError: need more than 1 value to unpack
我通过调用:
从命令行运行我的示例程序python ex13.py
答案 0 :(得分:5)
你的例子最好写成(以应对任意用法):
from sys import argv
script, args = argv[0], argv[1:]
print("The script is called: ", script)
for i, arg in enumerate(args):
print("Arg {0:d}: {1:s}".format(i, arg))
您收到错误的原因( place show Traceback )是因为您使用的参数少于尝试“解压缩”而调用脚本。
请参阅:Python Packing and Unpacking和Tuples and Sequences,其中包含:
这足够恰当地称为序列解包并且适用于 右侧的任何序列。序列拆包需要 左边的变量列表具有相同数量的元素 序列的长度。请注意,实际上是多次分配 只是元组打包和序列解包的组合。
为了证明您的示例adn eht错误发生了什么,您会回来:
>>> argv = ["./foo.py", "1"]
>>> script, a = argv
>>> script
'./foo.py'
>>> a
'1'
>>> script, a, b = argv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
这里的错误很明显;您正在尝试解除比您更多的值!
为了解决你的例子,我会这样做:
from sys import argv
if len(argv) < 4:
print ("usage: {0:s} <bike> <car> <bus>".format(script))
raise SystemExit(-1)
script, bike, car, bus = argv
print ("The script is called:", script)
print ("The first variable is:", bike)
print ("The second variable is ", car)
print ("Your third variable is : ", bus)
更新:我刚注意到这一点;但你所有的print()
都错了。您需要使用str.format()
或将参数放在print()
函数中。
答案 1 :(得分:3)
Pycharm是一个ide,我只需单击run并运行程序,但在powershell中我输入python ex13.py并运行程序
好的,那么你没有传递任何参数。那么,你期待什么找到第一,第二和第三个参数? PowerShell不会猜测你想要通过该计划的自行车,汽车和公共汽车,除了它会外出并给你买一辆自行车,汽车和公共汽车。所以,如果你想用代表你的自行车,汽车和公共汽车的参数运行这个程序,你必须实际做到这一点:
python ex13.py CR325 Elise VW
然后您的脚本将输出这些参数。
嗯,实际上,它可能没有,因为您的print
来电是错误的。如果这是Python 2.7,那些括号不会做任何事情,所以你会看到:
The script is called: ex13.py
The first variable is: CR325
The second variable is Elise
The third variable is : VW
如果它是Python 3.x,则括号将参数包装到print
,就像任何其他函数一样,因此, script
等不是print
的一部分,所以你只会看到:
The script is called:
The first variable is:
The second variable is
The third variable is :