我需要多个值才能解压缩值错误

时间:2016-08-18 01:46:14

标签: python

这是我的程序

Traceback (most recent call last):
  File "C:/Users/ravikishore/PycharmProjects/Test/.idea/MyPython.py", line 2, in <module>
    [script, first, second, third] = argv
ValueError: need more than 1 value to unpack

错误是:

namespace example
{
    class Program
    {
    public static StreamWriter[] writer = new StreamWriter[3];

    static void Main(string[] args)
    {
        writer[0] = new StreamWriter("YourFile1.txt");
        writer[1] = new StreamWriter("YourFile2.txt");
        writer[2] = new StreamWriter("YourFile3.txt");

        writer[0].WriteLine("Line in YourFile1.");
        writer[1].WriteLine("Line in YourFile2.");
        writer[2].WriteLine("Line in YourFile3.");

        writer[0].Close();
        writer[1].Close();
        writer[2].Close();
    }
}

2 个答案:

答案 0 :(得分:3)

argv是一个列表:

>>> from sys import argv
>>> type(argv)
<type 'list'>

因此,您尝试从列表转换为元组,仅当元组完全中的元素数与列表长度匹配时才有效:

>>> a,b,c = [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
>>> a,b,c = [1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
>>> a,b,c = [1,2,3]
>>> a,b,c = [1,2,3,4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

因此,您需要在尝试转换之前在argv长度上添加一些检查。

答案 1 :(得分:2)

该代码只是很好,假设你实际上给它它解压三个参数,如:

c:\pax> python yourProg.py A B C
the script is: yourProg.py
the first variable is: A
the second variable is: B
the third variable is: C

如果没有给它足够的论据,就会出现问题:

c:\pax> python yourProg.py A
Traceback (most recent call last):
  File "yourProg.py", line 2, in <module>
    script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 2)

如果您想在尝试解压缩之前确保有足够的参数,可以使用len(argv)来获取参数计数,并将其与您需要的参数进行比较,例如:

import sys
if len(sys.argv) != 4:
    print("Need three arguments after script name")
    sys.exit(1)
script, first, second, third = sys.argv
print ("the script is:", script)
print("the first variable is:", first)
print("the second variable is:", second)
print ("the third variable is:", third)