Search code examples
pythoncommand-linearguments

When I am using command line arguments, why is Python counting my file name as a value?


I have tried to fix it and have looked over my code many times, but nothing really seems wrong.

I had unpacked the module to 3 values and tried run the program, but it gave me the error that I was giving too many values:

PS C:\dir1> python exlp.py ramen lucid chubby

Traceback (most recent call last):

  File "exlp.py", line 54, in <module>

    ramen, lucid, chubby = argv

ValueError: too many values to unpack

After a while I figured out that it was counting the file name as a value. I have no clue why this is happening, but here is my code:

from sys import argv

sakura, ramen, lucid, chubby = argv

print "You love...", sakura
print "You like to eat...", ramen
print "Your dreams are...", lucid
print "You are...", Naruto

print raw_input('Do you know someone named Naruto?')

Thank you!


Solution

  • Because that's what it does.

    sys.argv

    The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

    To loop over the standard input, or the list of files given on the command line, see the fileinput module.

    Either account for that value or slice that list:

    _, ramen, lucid, chubby = argv # option 1
    ramen, lucid, chubby = argv[1:] # option 2