Examples
Python Command-Line Args
Parsing Command-Line Arguments
Python command-line args use argparse for flexible CLI parsing.
Introduction to Python Command-Line Arguments
Command-line arguments are a way to provide inputs to a Python script from the command line. Python's argparse
module offers a flexible way to process these arguments, allowing developers to create robust command-line interfaces (CLI) for their applications.
In this tutorial, we'll explore how to use argparse
to handle command-line arguments effectively.
Setting Up argparse
To begin using argparse
, you need to import the module and create an ArgumentParser
object. This object will hold all the information necessary to parse the command line arguments.
Adding Arguments
Once you have an ArgumentParser
object, you can start adding arguments. Each argument can have various attributes such as type, help message, and default value. Let's add a couple of arguments to our parser.
Parsing Arguments
After defining the arguments, use the parse_args()
method to parse the command-line arguments. This method returns an object containing the parsed arguments, which you can access as attributes.
Running the Script
To see the argparse
module in action, save your script and run it from the command line. For example:
python script.py --name Alice --age 28
This will output:
Hello, Alice! You are 28 years old.
Examples
- Previous
- JSON Processing
- Next
- Logging Setup