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

import sys;                                                                     
print sys.argv;   
$ python 1 2 3
['', '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
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.
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))); 
$ python 1 2 3 "commandline args"
Command Line Arguments Count: 5
Argument 0:
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])
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).
import sys, getopt                                                              
def parse_command_line_options(argv):                                           
    source_file = "";                                                           
    dest_file =  "";                                                            
        # 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(" -s  -d ");        
    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__":                                                      
Differnt Scenario's Output:
# if no options are given in command line arguments
$ python 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 -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 -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 -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 -h "file_output.txt" -s  -d 

# if s option with no argument value, then raises exception and prints message.
$ python -s -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