3 Easy Ways to Handle Command Line Arguments in Python

Himanshu Pathak 13 Mar, 2024 β€’ 3 min read

Introduction

Welcome to another exciting journey into the world of Python! In this blog we will be exploring a fundamental yet often overlooked aspect of Python scripting – Command Line Arguments. These are inputs that you pass to your Python script at the time of running it. They are incredibly useful for making your scripts flexible and reusable.

Let’s dive in and discover three easy ways to get command line arguments in Python.

Command Line Arguments

The Basics of Command Line Arguments

Command line arguments are parameters that are specified after the name of the program in the command line shell of your operating system. Python provides several ways of reading these arguments, which can be very useful when you’re writing scripts that need to take in varying inputs. The most common use cases include specifying configuration options or input data files.

Elevate your Python skills. Explore command line arguments with real-world examples.

Join our free Python course for hands-on learning!

How to pass Command Line Arguments?

If we have a python script which generates 5 Random numbers between two numbers 1 to 100, which accepts these 3 integers as Command Line Arguments.

Syntax:-

Command_Name Name_of_the_python_script arg1 arg2 arg3

Example:

python generate_random.py 1 100 5

Explanation:-

python β†’ Command_Name

Generate_random.py β†’ Name_of_the_python_script

1,100 & 5 β†’ Command Line Arguments (arg1, arg2, arg3)

Also Read: How To Convert Python Dictionary To JSON?

Using sys.argv

The simplest way to handle command line arguments in Python is by using the sys module’s argv. The argv is a list in Python, which contains the command-line-arguments passed to the script. The first argument, argv[0], is always the script name itself.

Let’s look at a simple example:

Example:

import sys

print("Script Name is:", sys.argv[0])

print("Arguments are:", sys.argv[1:])

Command Line Interface:

python generate_random.py 1 100 5

Output:

Script Name is:generate_random.py

Arguments are:[1,100,5]

Using getopt Module

The getopt module is a more powerful tool for parsing command line arguments. It offers functions like getopt() and gnu_getopt() that parse argument lists and return a tuple containing two lists. The first list contains simple options, and the second list contains arguments that are associated with some option. Here’s how you can use it:

Example:

import sys

import getopt

try:

   opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])

except getopt.GetoptError as err:

   print(err)

# Process options

for opt, arg in opts:

   if opt in ("-h", "--help"):

       print("Help Needed")

   elif opt in ("-o", "--output"):

      print("Arguments Passed with -o Option:-",arg)

Command Line Interface

python CML.py -h

Output:

Help Needed

Command Line Interface:

python CML.py -o 5

Output:

Arguments Passed with -o Option:- 5

Using argparse Module

Argparse is the recommended command-line parsing module in Python’s standard library. It’s the in-built solution for command line arguments. It creates a parser that reads command-line arguments, where you can specify what options the command-line of your script should have.

Here’s a simple example:

Example:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--arguments", help="insert argg")

args = parser.parse_args()

print(args.arguments.lower())

Command Line Interface:

python Lower.py --arguments Hi,Himanshu

Output:

hi,himanshu

Conclusion

Command line arguments are a powerful tool for making your Python scripts more flexible and reusable. They allow you to pass different inputs to your script each time you run it, making it more versatile. We’ve explored three easy ways to handle command line arguments in Python – using sys.argv, the getopt module, and the argparse module. Each method has its own strengths and weaknesses, so choose the one that best fits your need.

Enroll in our free Python course for practical insights and coding mastery.

Frequently Asked Questions

Q1. What are command line arguments in Python?

A. Command line arguments in Python are inputs provided to a script during execution, enhancing script versatility by allowing dynamic parameterization.

Q2. What are command line arguments with examples?

A. Command line arguments are values passed after the script name. Example: “python script.py arg1 arg2,” where arg1 and arg2 are command line arguments.

Q3. How do you write a command line in Python?

A. Writing a command line in Python involves using sys.argv, getopt, or argparse modules. These enable handling and parsing of inputs for script customization.

Q4. How do you give an argument in Python?

A. Provide arguments by appending values after the script name during execution.
Example: “python script.py arg1 arg2” assigns arg1 and arg2

Himanshu Pathak 13 Mar 2024

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear