Python Command Line Arguments
Command line arguments allow users to pass input values to a Python program directly from the terminal while executing the script. This feature is extremely useful when building command-line tools, automation scripts, or data processing programs where input needs to be provided dynamically.
Instead of hardcoding values inside a program, command line arguments allow the user to provide data during execution.
What are Command Line Arguments?
Command line arguments are parameters passed to a Python script when it is executed from the command line. These arguments can be accessed within the Python program and used for processing tasks such as file handling, configuration settings, or data processing.
Example command:
Here, John and 25 are command line arguments passed to the script.
Using sys.argv
Python provides the sys module to access command line arguments using sys.argv.
The argv list contains the following elements:
- argv[0] – Name of the script
- argv[1] – First argument
- argv[2] – Second argument
Running the program:
Output:
Script name: script.py First argument: Alice Second argument: 30
Handling Multiple Arguments
You can process multiple arguments using loops.
This will print all arguments passed to the script.
Converting Arguments to Numbers
Command line arguments are received as strings, so they must be converted if numeric operations are required.
Execution:
This program calculates the sum of two numbers provided through the command line.
Checking Number of Arguments
To avoid errors, it is good practice to check whether the required number of arguments is provided.
This ensures that the program does not crash due to missing arguments.
Using argparse Module
For more advanced command-line tools, Python provides the argparse module. It allows defining arguments, help messages, and default values.
This approach provides better argument handling and automatic help messages.
Displaying Help Message
The argparse module automatically generates help documentation.
This command displays usage instructions for the script.
Real-World Example
Command line arguments are commonly used in automation scripts such as file processors.
This program reads a file whose name is provided through the command line.
Best Practices for Command Line Arguments
- Always validate user input.
- Use argparse for complex command-line tools.
- Provide helpful error messages.
- Document script usage clearly.
Conclusion
Command line arguments allow Python programs to receive input directly from the terminal, making scripts more flexible and interactive. By using modules like sys and argparse, developers can build powerful command-line applications for automation and data processing.
Understanding command line arguments is an essential step toward building professional Python tools and utilities.
In the next tutorial, we will explore Working with APIs in Python and learn how Python communicates with web services.

