Python Command line arguments

The Python supports the programs that can be run on the command line, complete with command line arguments. It is the input parameter that needs to be passed to the script when executing them. It means to interact with a command-line interface for the scripts. There are different ways we can use command line arguments, few of them are:

1. Python sys module

It is a basic module that comes with Python distribution from the early versions. It is a similar approach as C library using argc/argv to access the arguments. The sys module implements command-line arguments in a simple list structure named sys.argv.

Each list element represents a single argument. The first one — sys.argv[0] — is the name of Python script. The other list elements are sys.argv[1] to sys.argv[n]- are the command line arguments 2 to n. As a delimiter between arguments, space is used. Argument values that contain space in it have to be quoted, accordingly.

It stores command-line arguments into a list; we can access it using sys.argv. This is very useful and a simple way to read command-line arguments as String.

Code

import sys  

# Check the type of sys.argv  

print(type(sys.argv))  #  <class ' list '>  

# Print the command line arguments  

print(' The command line arguments are: ')  

# Iterate over sys.argv and print each argument  

for i in sys.argv:  

    print(i)

Output:<class ‘ list ‘> The command line arguments are: script.py arg1 arg2

2. Python getopt module

The Python getopt module extends the separation of the input string by parameter validation. Based on getopt C function, it allows both short and long options, including a value assignment.

It is very similar to C getopt() function for parsing command line parameters.

It is useful in parsing command line arguments where we want the user to enter some options.

Code

import getopt  

import sys  

argv = sys.argv[1:]  

try:  

    opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])  

    print(opts)  

    print(args)  

except getopt.GetoptError:  

    # Print a message or do something useful  

    print('Something went wrong!')  

    sys.exit(2)

Output:[(‘-h’, ”), (‘-m’, ‘my_value’), (‘–my_file’, ‘input.txt’)] [‘arg1’, ‘arg2’]

3. Python argparse module

It offers a command-line interface with standardized output, whereas the former two solutions leave most of the work in your hands. argparse allows verification of fixed and optional arguments with a name checking as either UNIX or GNU style. It is the preferred way to parse command-line arguments. It provides a lot of option such as positional arguments, the default value for arguments, helps message, specifying the data type of argument etc.

It makes it easy to write the user-friendly command-line interfaces. It automatically generates help and usage messages and issues errors when a user gives invalid arguments to the program. It means to communicate between the writer of a program and user which does not require going into the code and making changes to the script. It provides the ability to a user to enter into the command-line arguments.

Code

import argparse  

  

# Create an ArgumentParser object  

parser = argparse.ArgumentParser(description = 'Example script using argparse')  

  

# Add arguments  

parser.add_argument('-f',  '--file', help = 'Specify a file name')  

parser.add_argument('-v', '--verbose', action = 'store_true', help = 'Enable verbose mode')  

  

# Parse the command line arguments  

args = parser.parse_args()  

  

# Access the argument values  

if args.file:  

    print(f "File name : {args.file} ")  

if args.verbose:  

    print("Verbose mode is enabled")

Output:python script.py -f myfile.txt -v File name : myfile.txt Verbose mode is enabled

The above three are the common basic modules to operate command line arguments in Python. Other simple modules in Python for command line arguments are:

Docopt

Docopt is used to create command line interfaces. It simplifies the process of parsing command-line arguments and generating help messages. To use docopt, you need to install the library first. You can install it using pip:

Code

from docopt import docopt  

  

__doc__  =  """Usage: 

    my_program.py [--option1] [--option2=<value>] <argument> 

 

Options: 

    -h, --help         Show this help message. 

    -o, --option1      Enable option 1. 

    -t, --option2 = <value>  Specify option 2 value. 

"""  

  

if __name__ == '__main__':  

    arguments = docopt(__doc__, version = 'Example 1')  

    print(arguments)

Output:$ python script.py –option1 –option2=value argument_value { ‘–help’: False, ‘–option1’: True, ‘–option2’: ‘value’, ‘ ‘: ‘ argument_value ‘, ‘–version’: False }

Fire

Python Fire automatically generates a command line interface; you only need one line of code. Unlike the other modules, it works instantly. You don’t need to define any arguments; all the methods are linked by default. To install it, type:

pip install fire  

Define or use a class:

Code

import fire    

class Python(object):    

    def hello(self):    

    print("Hello")    

       def openfile(self, filename):    

        print(" Open file  '" + filename + "'")    

    

if __name__ == '__main__':    

    fire.Fire(Python)

Output:$ python script.py hello Hello $ python script.py openfile my_file.txt Open file ‘my_file.txt’

Command Line arguments Modules

ModuleUsePython version
sysAll arguments in sys.argv (basic)All
argparseBuild a command line interface>= 2.3
docoptCreated command line interfaces>= 2.5
fireAutomatically generate command line interfaces (CLIs)All
optparseDeprecated< 2.7

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *