26

I am not getting the desired output for this program:

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)

How to use CMD to pass these arguments?

Tomerikoo
19.6k16 gold badges57 silver badges68 bronze badges
asked Sep 19, 2015 at 21:28

1 Answer 1

32

You call it like

python program.py a1 b2 c3

and it outputs

The script is called: /home/sophia/program.py
Your first variable is: a1
Your second variable is: b2
Your third variable is: c3

sys.argv contains list of strings, each corresponding to a command line parameter. First one is always the filename of the script; others are the optional parameters, ordered exactly as they were typed in a shell.

Note that the code you provided works correctly only when you pass exactly three parameters due to the tuple unpacking.

See the docs for sys.argv and also check out argparse module documentation if you are going to write a program handling lots of arguments.

answered Sep 19, 2015 at 21:32
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.