1

I am new to python programming and I tried this code:

from sys import argv


script, first, second, third = argv
print "this script is called:" ,script

print "the first variable is called : " ,first

print "the second variable is called : ", second

print "the third variable is called : " ,third

I am getting the error :

Traceback (most recent call last):
  File "/Users/richavarma/Documents/first.py", line 4, in <module>
    script, first, second, third = argv
ValueError: need more than 1 value to unpack

My output should be as follows:

this script is called: abc.py
the first variable is called: first
the second variable is called : second
the third variable is called : third
15
  • Can you show us how you are executing the script? Commented May 21, 2017 at 3:52
  • 1
    Your program works on my end: python untitled.py 1 2 3 this script is called: untitled.py the first variable is called : 1 the second variable is called : 2 the third variable is called : 3 Commented May 21, 2017 at 3:54
  • 4
    My guess is that the error means you're not passing in any command line arguments. If I were you I would add a guard to check the number of arguments passed in to exit gracefully. Could you show us how you're executing your script? Commented May 21, 2017 at 3:54
  • 1
    @Richa that's the problem alright. sys.argv expects command line options. You can't do that from IDLE. Try running it from shell with command line args (like in rth's example) Commented May 21, 2017 at 4:03
  • 1
    Please post your terminal command line which return an error. Again on my side everything works. Commented May 21, 2017 at 4:38

1 Answer 1

1

In short, argv takes arguments from the command line. If you type this command into the command line:

python test.py first second third

You will pass 4 arguments to your python code: test.py, first, second, and third You can take in all 4 arguments as inputs by assignment like so:

from sys import argv

(filename, arg1, arg2, arg3) = argv

After this you can use any of the arguments as strings with their variable names.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.