— 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.
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 h2 | | |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 return7
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 516All 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 523All Arguments : ['cliargs3.py', '1', '2', '3', '4', '5']24
25(base) D:\BigData\12. Python\5. BTD\progs>python cliargs3.py 126All 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,
sys.argv[1:]
(leaving program name)'x:y:'
["help", "period=", ""]
When calling,
python cliargs3.py -x 1 -y 2 3 4 5
)python cliargs2.py --period H
)Below is a simple example using getopt,
1import getopt2import sys3 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 arguments12print('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 517Options 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 521Options 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 arguments2import 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 = suffixed16 long_options = ["help", "period=", ""] 17 period_long = {"Q":"Quarterly", "H":"Half yearly", "Y":"Yearly"}18
19 # Initializing default20 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 argument28 for currentArgument, currentValue in arguments:29 currentArgument = currentArgument.lower() # Converting all options to lowercase30 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 period52
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 help62(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py --help63All Arguments : ['cliargs2.py', '--help']64Argument list : ['--help']65Diplaying Help. Options available66* cliargs.py -p Q = Process Quarterly67* cliargs.py -p H = Process Half yearly68* cliargs.py -p Y = Process Yearly69Chosen option is -70
71Output 2 : Long Options period72(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py --period H73All Arguments : ['cliargs2.py', '--period', 'H']74Argument list : ['--period', 'H']75Process Half yearly76Chosen option is H77
78Output 3 : Short Options help79(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py -h80All Arguments : ['cliargs2.py', '-h']81Argument list : ['-h']82Diplaying Help. Options available83* cliargs.py -p Q = Process Quarterly84* cliargs.py -p H = Process Half yearly85* cliargs.py -p Y = Process Yearly86Chosen option is -87
88Output 4 : Short Options period89(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py -p y90All Arguments : ['cliargs2.py', '-p', 'y']91Argument list : ['-p', 'y']92Process Yearly93Chosen option is Y94
95Output 5 : In long form don't have mention full option name as long as its unique96(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py --he97All Arguments : ['cliargs2.py', '--he']98Argument list : ['--he']99Diplaying Help. Options available100* cliargs.py -p Q = Process Quarterly101* cliargs.py -p H = Process Half yearly102* cliargs.py -p Y = Process Yearly103Chosen option is -104
105(base) D:\BigData\12. Python\5. BTD\progs>python cliargs2.py --pe h106All Arguments : ['cliargs2.py', '--pe', 'h']107Argument list : ['--pe', 'h']108Process Half yearly109Chosen option is H
Thats it for now, go PLAY