3 Easy Ways to Handle Command Line Arguments in Python

Himanshu Pathak Last Updated : 18 Nov, 2024
4 min read

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 argument to 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

Learning Objectives:

  • Understand the concept of command-line arguments and their purpose in Python scripting
  • Learn how to pass argument to python script when running a Python script
  • Explore three different methods to handle command-line arguments: sys.argv, getopt module, and argparse module
  • Gain the ability to write Python scripts that accept and process command-line inputs

In this article, you will learn about command line arguments in Python and how to use them effectively. Specifically, we will explore how to add two numbers using command line arguments in Python. You will discover how to take command line arguments in Python, as well as how to get command line arguments in Python for various applications. This knowledge will enhance your ability to create dynamic and interactive Python scripts.

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 is by using the sys module’s argv. The argv is a list in Python, which contains the command-line-arguments pass argument to python 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 args to python script 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 – 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.

Checkout this article about Python Programming for Beginners

Key Takeaways:

  • Command-line arguments allow you to pass args to python script inputs to a Python script during execution, making it more flexible and reusable
  • The sys.argv approach is the simplest method, but it provides basic functionality for parsing arguments
  • The getopt module offers more powerful argument parsing capabilities, including options and associated arguments
  • The argparse module is the recommended and most robust way to handle command-line arguments in Python scripts
  • Mastering command-line arguments enables you to create versatile Python scripts that can be customized and parameterized

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 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 to get an argument from a command line in Python?

A. To get command-line arguments in Python, use the argparse module:
Import: import argparse
Create Parser: parser = argparse.ArgumentParser()
Add Arguments: parser.add_argument()
Parse Arguments: args = parser.parse_args()
Access Arguments: args.argument_name

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details