YouTip LogoYouTip

Python Command Line Arguments

# Python2.x Python Command-Line Arguments [![Image 3: Python Basic Syntax](#) Python Basic Syntax](#) Python provides the **getopt** module to get command-line arguments. $ python test.py arg1 arg2 arg3 Python can also use **sys**'s **sys.argv** to get command-line arguments: * sys.argv is the list of command-line arguments. * len(sys.argv) is the number of command-line arguments. **Note:** sys.argv represents the script name. ### Example The code for the test.py file is as follows: ## Example #!/usr/bin/python # -*- coding: UTF-8 -*- import sys print'Number of arguments:',len(sys.argv),'arguments.' print'Argument list:',str(sys.argv) Executing the above code, the output result is: $ python test.py arg1 arg2 arg3 Number of arguments: 4 arguments. Argument list: ['test.py', 'arg1', 'arg2', 'arg3'] * * * ## getopt Module The getopt module is specifically designed for handling command-line arguments, used to get command-line options and arguments, i.e., sys.argv. Command-line options make the program's arguments more flexible. It supports short option mode - and long option mode --. This module provides two methods and one exception handling to parse command-line arguments. ### getopt.getopt Method The getopt.getopt method is used to parse the command-line argument list. The syntax format is as follows: getopt.getopt(args, options[, long_options]) Method parameter description: * **args**: The command-line argument list to be parsed. * **options**: Defined in string format. The colon : after **options** indicates that if this option is set, it must have an additional parameter; otherwise, no additional parameter is attached. * **long_options**: Defined in list format. The equals sign = after **long_options** indicates that this option must have an additional parameter; without the equals sign indicates that this option does not take an additional parameter. * The return value of this method consists of two elements: the first is a list of **(option, value)** tuples. The second is the argument list, containing those arguments that do not have **-** or **--**. Another method is getopt.gnu_getopt, which will not be discussed in detail here. * * * ## Exception getopt.GetoptError This exception is triggered when the argument list is not found, or the required parameter for an option is empty. The exception parameter is a string indicating the cause of the error. The attributes **msg** and **opt** are the error messages for the related option. ### Example Assume we create a script that can pass two filenames to the script file via the command line, and we also use another option to view the script's usage. The script usage is as follows: usage: test.py -i -o The code for the test.py file is as follows: ## Example #!/usr/bin/python # -*- coding: UTF-8 -*- import sys,getopt def main(argv): inputfile ='' outputfile ='' try: opts, args =getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print'test.py -i -o ' sys.exit(2) for opt, arg in opts: if opt =='-h': print'test.py -i -o ' sys.exit() elif opt in("-i","--ifile"): inputfile = arg elif opt in("-o","--ofile"): outputfile = arg print'Input file is:', inputfile print'Output file is:', outputfile if __name__ =="__main__": main(sys.argv[1:]) Executing the above code, the output result is: $ python test.py -h usage: test.py -i -o $ python test.py -i inputfile -o outputfile Input file is: inputfile Output file is: outputfile [![Image 4: Python Basic Syntax](#) Python Basic Syntax](#)
← Python3 Func Number AbsPython Command Line Arguments β†’