Search code examples
pythonpyscripter

PyScripter - import argv error


I am using "Learn Python the Hard Way" and using PyScripter for writing and running my code.

On Exercise 13 I have to make the following code run:

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

When I run it, I get an error saying

ValueError: need more than 1 value to unpack

I have read other questions about the same topic and can't seem to find an answer that works.

I am also quite new to coding so explaining how to do it would be great!


Solution

  • Your script will only work if you pass exactly three commandline arguments to it. For example:

    script.py 1 2 3
    

    You cannot use any other number of commandline arguments or else a ValueError will be raised.

    Perhaps you should make your script a little more robust by checking how many arguments you received and then assigning the names first, second, and third appropriately.

    Below is a demonstration:

    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
    

    Of course, this is just an example. You can do anything you want inside the if-statements (assign the names to something different, raise an exception, print a message, exit the script, etc.). The important part here is the argc = len(argv) line and the if-statements which check how many arguments the script received.