Command-line arguments are parameters that you pass to a program when you run it from the command line or terminal. They allow you to provide input to the program at runtime, enabling dynamic behavior based on user input.
How Command-Line Arguments Work:
-
Accessing Arguments:
- In Python, you can access command-line arguments using the
sysmodule or theargparsemodule. - The
sys.argvlist contains the command-line arguments passed to the script. The first element (sys.argv[0]) is the name of the script itself, and the subsequent elements are the arguments.
- In Python, you can access command-line arguments using the
-
Using
argparse:- The
argparsemodule provides a more powerful way to handle command-line arguments, allowing you to define expected arguments, types, and help messages. - You can specify required and optional arguments, as well as flags.
- The
Example Using argparse:
Here’s a simple example of a Python script that uses argparse to handle command-line arguments:
import argparse
# Create the parser
parser = argparse.ArgumentParser(description='A simple command-line argument example.')
# Add arguments
parser.add_argument('name', type=str, help='Your name')
parser.add_argument('--greet', action='store_true', help='Greet the user')
# Parse the arguments
args = parser.parse_args()
# Use the arguments
if args.greet:
print(f"Hello, {args.name}!")
else:
print(f"Goodbye, {args.name}!")
Running the Script:
You can run this script from the command line as follows:
python script.py Alice --greet
This would output:
Hello, Alice!
If you omit the --greet flag:
python script.py Alice
It would output:
Goodbye, Alice!
Summary:
Command-line arguments provide a way to pass information to scripts at runtime, allowing for flexible and dynamic program behavior.
