Skip to content
bobby_dreamer

Python simple command line arguments

python1 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

1python cliarg.py -p h
2 | | |
3 | | |-- Arg2 ( option value )
4 | |----- Arg1 ( option )
5 |--------------- Arg0 ( program name )

Below is a simple example using sys.argv,

1import sys
2
3def process_args():
4 print ('All Arguments :', str(sys.argv))
5 print(sys.argv[0])
6 return
7
8def main():
9 period = process_args()
10
11if __name__ == "__main__":
12 main()
13
14Output :
15(base) D:\BigData\12. Python\5. BTD\progs>python cliargs3.py 1 2 3 4 5
16All Arguments : ['cliargs3.py', '1', '2', '3', '4', '5']
17cliargs3.py

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.

1import getopt, sys
2
3def process_args():
4 print ('All Arguments :', str(sys.argv))
5
6 try:
7 if len(sys.argv) < 3:
8 raise ValueError('Less arguments')
9
10 except ValueError as err:
11 print (str(err))
12 return
13
14def main():
15 process_args()
16
17
18if __name__ == "__main__":
19 main()
20
21Output :
22(base) D:\BigData\12. Python\5. BTD\progs>python cliargs3.py 1 2 3 4 5
23All Arguments : ['cliargs3.py', '1', '2', '3', '4', '5']
24
25(base) D:\BigData\12. Python\5. BTD\progs>python cliargs3.py 1
26All Arguments : ['cliargs3.py', '1']
27Less arguments

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(:)
    • like 'x:y:'
  • 3rd argument(optional), long-form option names, verbose. If an option has an argument then that option should be followed by equal sign(=)
    • like ["help", "period=", ""]

When calling,

  • 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,

1import getopt
2import sys
3
4argv = sys.argv[1:]
5
6opts, args = getopt.getopt(argv, 'x:y:')
7
8# list of options tuple (opt, value)
9print('Options Tuple is {}'.format(opts))
10
11# list of remaining command-line arguments
12print('Additional Command-line arguments list is {}'.format(args))
13
14
15Output :
16(base) D:\BigData\12. Python\5. BTD\progs>python cliargs3.py -x 1 -y 2 3 4 5
17Options Tuple is [('-x', '1'), ('-y', '2')]
18Additional Command-line arguments list is ['3', '4', '5']
19
20(base) D:\BigData\12. Python\5. BTD\progs>python cliargs3.py -y 2 -x 1 3 4 5
21Options Tuple is [('-y', '2'), ('-x', '1')]
22Additional Command-line arguments list is ['3', '4', '5']

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

1# Python program to demonstrate Command line arguments
2import getopt, sys
3
4def process_args():
5 # Remove 1st argument from the
6 # list of command line arguments
7
8 print ('All Arguments :', sys.argv)
9 argumentList = sys.argv[1:]
10 print ('Argument list :', argumentList)
11
12 # Options (p requires an argument, thats why it has :)
13 options = "hp:"
14
15 # Long options : 'period=' requires an argument, so it has = suffixed
16 long_options = ["help", "period=", ""]
17 period_long = {"Q":"Quarterly", "H":"Half yearly", "Y":"Yearly"}
18
19 # Initializing default
20 period = 'Q'
21 try:
22 # Parsing argument
23 arguments, remainder = getopt.getopt(argumentList, options, long_options)
24 if(len(remainder)> 0):
25 print('Other options = {}'.format(remainder))
26
27 # checking each argument
28 for currentArgument, currentValue in arguments:
29 currentArgument = currentArgument.lower() # Converting all options to lowercase
30 if currentArgument in ("-h", "--help"):
31 print ("Diplaying Help. Options available")
32 print ("* {} -p Q = Process Quarterly".format('cliargs.py'))
33 print ("* {} -p H = Process Half yearly".format('cliargs.py'))
34 print ("* {} -p Y = Process Yearly".format('cliargs.py'))
35 period = '-'
36 elif currentArgument in ("-p", "--period"):
37 if(currentValue.lower() in [x.lower() for x in ['Q', 'H', 'Y']]):
38 period = currentValue.upper()
39 print('Process {}'.format(period_long[period]))
40 else:
41 period = 'Q'
42 print('Process Quarterly(default)')
43
44 except getopt.error as err:
45 # output error, and return with an error code
46 print (str(err))
47 print ("Diplaying Help. Options available")
48 print ("* {} -p Q = Process Quarterly".format('cliargs.py'))
49 print ("* {} -p H = Process Half yearly".format('cliargs.py'))
50 print ("* {} -p Y = Process Yearly".format('cliargs.py'))
51 return period
52
53def main():
54 period = process_args()
55 print('Chosen option is {}'.format(period))
56
57if __name__ == "__main__":
58 main()
59
60
61Output 1 : Long Options help
62(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py --help
63All Arguments : ['cliargs2.py', '--help']
64Argument list : ['--help']
65Diplaying Help. Options available
66* cliargs.py -p Q = Process Quarterly
67* cliargs.py -p H = Process Half yearly
68* cliargs.py -p Y = Process Yearly
69Chosen option is -
70
71Output 2 : Long Options period
72(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py --period H
73All Arguments : ['cliargs2.py', '--period', 'H']
74Argument list : ['--period', 'H']
75Process Half yearly
76Chosen option is H
77
78Output 3 : Short Options help
79(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py -h
80All Arguments : ['cliargs2.py', '-h']
81Argument list : ['-h']
82Diplaying Help. Options available
83* cliargs.py -p Q = Process Quarterly
84* cliargs.py -p H = Process Half yearly
85* cliargs.py -p Y = Process Yearly
86Chosen option is -
87
88Output 4 : Short Options period
89(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py -p y
90All Arguments : ['cliargs2.py', '-p', 'y']
91Argument list : ['-p', 'y']
92Process Yearly
93Chosen option is Y
94
95Output 5 : In long form don't have mention full option name as long as its unique
96(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py --he
97All Arguments : ['cliargs2.py', '--he']
98Argument list : ['--he']
99Diplaying Help. Options available
100* cliargs.py -p Q = Process Quarterly
101* cliargs.py -p H = Process Half yearly
102* cliargs.py -p Y = Process Yearly
103Chosen option is -
104
105(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py --pe h
106All Arguments : ['cliargs2.py', '--pe', 'h']
107Argument list : ['--pe', 'h']
108Process Half yearly
109Chosen option is H

Thats it for now, go PLAY