Python simple command line arguments
— python — 1 min read
Command line arguments are basically instructions or inputs given to the program in the terminal or command prompt. This is almost essential for a program which run in the terminal. Its pretty much easy to setup.
Basics on CLI
If you want to use command line argument, you have to work with
sys.argv which gives out a list/array containing all the arguments you had passed to the program when running it and to use
sys.argv, you will first have to import the sys module.
Basically mapping would be like this
Below is a simple example using sys.argv,
Next thing is to check that the arguments are valid, here easiest thing to check is, right number of arguments are provided when executing the program. For this we can just count the number of arguments and raise error when wrong.
If you start progressing with this, you will come to know that arguments have to be in right order otherwise there would be error or codebase could get complex. So, easiest available option is to
import getopt module which parses command line options and parameter list. It can handle the 'right order' issue which i had mentioned.
getopt.getopt() takes in 3 arguments,
- 1st argument, sequence of arguments to be parsed. Input is from
sys.argv[1:](leaving program name)
- 2nd argument, short-form or single character options. If an option has an argument then that single character option should be followed by colon(:)
- 3rd argument(optional), long-form option names, verbose. If an option has an argument then that option should be followed by equal sign(=)
["help", "period=", ""]
- Short-form arguments are prefixed with single hypen(eg:
python cliargs3.py -x 1 -y 2 3 4 5)
- Long-form arguments are prefixed with double hypens(eg:
python cliargs2.py --period H)
Below is a simple example using getopt,
You can see the from the output, i had changed option order, but the tuple had the right values.
Now lets write a program which would take arguments from command line and if the arguments are wrong it would use the default. I have highlighted all the important lines
Thats it for now, now you go play snake charmer