PyScripter - 导入argv错误

时间:2014-12-07 20:54:58

标签: python pyscripter

我正在使用“以艰难的方式学习Python”并使用PyScripter编写和运行我的代码。

在练习13中,我必须运行以下代码:

from sys import argv


script, first, second, third = argv

print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third

当我运行它时,我收到错误说

ValueError: need more than 1 value to unpack

我已经阅读了有关同一主题的其他问题,似乎无法找到有效的答案。

我对编码也很陌生,所以解释如何做到这一点会很棒!

1 个答案:

答案 0 :(得分:0)

只有将完全三个命令行参数传递给它时,您的脚本才有效。例如:

script.py 1 2 3

您不能使用任何其他数量的命令行参数,否则将引发ValueError

也许您应该通过检查收到的参数数量,然后适当地分配名称firstsecondthird来使脚本更加健壮。

以下是演示:

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-statements,用于检查脚本接收的参数数量。