Python argv不工作

2024-04-26 12:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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个值才能解压缩

^{pr2}$

从命令行调用我的程序:

python ex13.py

Tags: thefromimportissysscriptcarvariable
2条回答

Pycharm is an ide and i just click run and it runs the program, but in powershell i type in python ex13.py and that runs the program

好吧,那你就不能传递任何论点了。那么,作为第一个,第二个,第三个论点,你期待着什么呢?PowerShell不会猜出你想通过什么样的自行车、汽车和公共汽车,就像它会出去给你买自行车、汽车和公共汽车一样。所以,如果你想用代表你的自行车、汽车和公共汽车的参数来运行这个程序,你就必须这样做:

python ex13.py CR325 Elise VW

然后脚本将输出这些参数。在

实际上,可能不是,因为你的print调用是错误的。如果这是Python 2.7,那么这些圆括号没有任何作用,因此您将看到:

^{pr2}$

如果是python3.x,括号将参数包装到print,就像任何其他函数一样,因此, script等不是{}的一部分,因此您将看到:

The script is called: 
The first variable is: 
The second variable is 
The third variable is : 

您的示例最好写为(以处理任意用法):

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 UnpackingTuples and Sequences,其中显示:

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

为了演示示例和eht错误发生了什么,请返回:

^{pr2}$

这里的错误应该很明显;您试图解压的值比您现有的要多!

为了修正你的例子,我会这样做:

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()都是错误的。您需要使用^{}或将参数放入print()函数中。在

相关问题 更多 >