Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Python Command Line Arguments: Essential Guide

Python Command line arguments are input parameters passed to the script when executing them. Almost all programming language provide support for command line arguments. Then we also have command line options to set some specific options for the program.

Options to Read Python Command Line Arguments

There are many options to read python command line arguments. The three most common ones are:

  • Python sys.argv
  • Python getopt module
  • Python argparse module

Python sys Module

Python sys module stores the command line arguments into a list, we can access it using sys.argv. This is very useful and simple way to read command line arguments as String. Let’s look at a simple example to read and print command line arguments using python sys module.

import sys

print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
    print(i)

Python getopt Module

Python getopt module is very similar in working as the C getopt() function for parsing command-line parameters. Python getopt module is useful in parsing command line arguments where we want user to enter some options too. Let’s look at a simple example to understand this.

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)

Above example is very simple, but we can easily extend it to do various things. For example, if help option is passed then print some user friendly message and exit. Here getopt module will automatically parse the option value and map them.

Python argparse Module

Python argparse module is the preferred way to parse command line arguments. It provides a lot of option such as positional arguments, default value for arguments, help message, specifying data type of argument etc. At the very simplest form, we can use it like below.

import argparse

parser = argparse.ArgumentParser()
parser.parse_args()

That’s all for different options to read and parse command line arguments in python, you should decide which is the one for your specific requirements and then use it. Python Command Line Arguments: Essential Guide

Start Your Cloud Journey Today with Our Free Trial!

Dive into the world of cloud computing with our exclusive free trial offer. Experience the power, flexibility, and scalability of our cloud solutions firsthand.

Try for free!