Python Command Line Arguments

Python Programming Language Command Line Arguments

  • Most of the utility scripts often require to process command line arguments
  • Command line arguments are stored in the sys module argv attribute as a list.

Example Command Line Arguments Python Program

#!/usr/bin/python                                                               
import sys;                                                                     
                                                                                
print sys.argv;   
Output:
$ python test_command_line_args.py 1 2 3
['test_command_line_args.py', '1', '2', '3']

Default Command Line Arguments

If you have not passed any arguments to the python scripts, default python scripts file name is added in sys module argv attibute list.
$ python test_command_line_args.py
['test_command_line_args.py']
Here sys.argv[0] is the python scripts file name.

sys module

  • Python sys module (argv attribute in sys module) is used to access any command-line arguments.
  • sys.argv is the list of command-line arguments.
  • len(sys.argv) is the number of command-line arguments.

Accessing Command Line Arguments

Following program is used to get command line arguments count and prints the command line arguments value with corresponding list index.
#!/usr/bin/python                                                               
import sys;                                                                     
                                                                                
print("Command Line Arguments Count: %d" % len(sys.argv));                      
for i, arg in enumerate(sys.argv):                                              
    print("Argument %d: %s" % (i, str(arg))); 
Output:
$ python test_command_line_args.py 1 2 3 "commandline args"
Command Line Arguments Count: 5
Argument 0: test_command_line_args.py
Argument 1: 1
Argument 2: 2
Argument 3: 3
Argument 4: commandline args

Parsing Command Line Arguments as Option and Argument Pairs

getopt module is available in python to parse the command-line options and arguments.

getopt.getopt method

getopt.getopt method parses command line options and arguments list.
getopt.getopt(command_line_arguments, options[, long_options])
Example
getopt.getopt(argv,"s:d:",["file1=","file2="]) 
here argv is th command line arguments, s and d are options but s requires aregument value mandatory otherwise throws getopt.GetoptError exception.
file1 and file2 are long options used to get option arguments.

Exception getopt.GetoptError

This exception is raised when an unrecognized option is found in the argument list or when an option requiring an argument but not given (none value).
#!/usr/bin/python                                                               
                                                                                
import sys, getopt                                                              
                                                                                
def parse_command_line_options(argv):                                           
    source_file = "";                                                           
    dest_file =  "";                                                            
    try:                                                                        
        # parsing command line arguments as option and argument pairs.          
        # here s and d are options                                              
        options, args = getopt.getopt(argv,"s:d:",["file1=","file2="])          
    except getopt.GetoptError:                                                  
        print("test_command_line_args.py -s  -d ");        
        sys.exit(1);                                                            
    for option, arg in options:                                                 
        if option in ("-s", "--file1"):                                         
            source_file = arg                                                   
        elif option in ("-d", "--file2"):                                       
            dest_file = arg                                                     
    print("Source file: %s" % source_file);                                     
    print("Destination file: %s" % dest_file);                                  
                                                                                
if __name__ == "__main__":                                                      
    parse_command_line_options(sys.argv[1:]);  
Differnt Scenario's Output:
# if no options are given in command line arguments
$ python test_command_line_args.py 1 2 3 "commandline args"
Source file: 
Destination file: 

# if both options are given with arguments in command line arguments
[jaganathan@dhcp35-211 python]$ python test_command_line_args.py -s "file_input.txt" -d "file_output.txt"
Source file: file_input.txt
Destination file: file_output.txt

# if both options are given but only s option has argument value in command line arguments
[jaganathan@dhcp35-211 python]$ python test_command_line_args.py -s "file_input.txt"
Source file: file_input.txt
Destination file: 

# if only d option is given with argument value in command line arguments
[jaganathan@dhcp35-211 python]$ python test_command_line_args.py -d "file_output.txt"
Source file: 
Destination file: file_output.txt

# if unknown option is given, raises exception and prints message
[jaganathan@dhcp35-211 python]$ python test_command_line_args.py -h "file_output.txt"
test_command_line_args.py -s  -d 

# if s option with no argument value, then raises exception and prints message.
$ python test_command_line_args.py -s 
test_command_line_args.py -s  -d 

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^