您的脚本只有在您将三个命令行参数传递给它时才能工作。例如:
script.py 1 2 3
您不能使用任何其他数量的命令行参数,否则ValueError
将引发 a。
也许您应该通过检查收到的参数数量然后适当地分配名称first
、、second
和来使您的脚本更健壮一些。third
下面是一个演示:
from sys import argv, exit
argc = len(argv) # Get the number of commandline arguments
if argc == 4:
# There were 3 commandline arguments
script, first, second, third = argv
elif argc == 3:
# There were only 2 commandline arguments
script, first, second = argv
third = '3rd'
elif argc == 2:
# There was only 1 commandline argument
script, first = argv
second = '2nd'
third = '3rd'
elif argc == 1:
# There was no commandline arguments
script = argv[0]
first = '1st'
second = '2nd'
third = '3rd'
else:
print "Too many commandline arguments"
exit(1)
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
当然,这只是一个例子。您可以在 if 语句中做任何您想做的事情(将名称分配给不同的名称、引发异常、打印消息、退出脚本等)。这里重要的部分是argc = len(argv)
检查脚本接收到多少参数的行和 if 语句。