Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass command line arguments in Python 3.x?

Tags:

I am not getting desired output of 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?

like image 309
InquisitiveSu Avatar asked Sep 19 '15 21:09

InquisitiveSu


People also ask

How do you use command line in Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do you pass command line arguments?

If you want to pass command line arguments then you will have to define the main() function with two arguments. The first argument defines the number of command line arguments and the second argument is the list of command line arguments.


1 Answers

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.

like image 158
Tigran Saluev Avatar answered Sep 20 '22 16:09

Tigran Saluev