Working with Optional Arguments
Optional arguments provide flexibility in command-line interfaces. Unlike positional arguments, optional arguments:
- Are prefixed with hyphens (typically
-
for short forms and --
for long forms)
- Can be omitted (the program will use default values if provided)
- Can be provided in any order
- Are ideal for configuration options that are not essential for the program to run
Let's create a program that demonstrates the use of optional arguments.
Creating a Greeting Program with Optional Arguments
-
In the WebIDE, create a new file called greeting.py
in the /home/labex/project
directory.
-
Add the following code to the file:
import argparse
## Create an argument parser
parser = argparse.ArgumentParser(description="A customizable greeting program")
## Add optional arguments
parser.add_argument("-n", "--name", default="World", help="The name to greet (default: World)")
parser.add_argument("-g", "--greeting", default="Hello", help="The greeting to use (default: Hello)")
parser.add_argument("-c", "--count", type=int, default=1, help="Number of times to display the greeting (default: 1)")
## Parse the arguments
args = parser.parse_args()
## Display the greeting
for _ in range(args.count):
print(f"{args.greeting}, {args.name}!")
-
Save the file.
-
Run the program without any arguments:
python /home/labex/project/greeting.py
- You should see the default greeting:
Hello, World!
- Now try customizing the greeting with optional arguments:
python /home/labex/project/greeting.py --name Alice --greeting Hi
- You should see the customized greeting:
Hi, Alice!
- You can also use the short forms of the arguments:
python /home/labex/project/greeting.py -n Bob -g Hey -c 3
- This should display the greeting three times:
Hey, Bob!
Hey, Bob!
Hey, Bob!
Types of Optional Arguments
argparse
supports several types of optional arguments:
-
Flag arguments: Boolean flags that are either present or not
-
Arguments with values: Optional arguments that take values
Let's modify our greeting program to include a flag argument:
-
Open greeting.py
in the WebIDE.
-
Add a flag argument for uppercase:
import argparse
## Create an argument parser
parser = argparse.ArgumentParser(description="A customizable greeting program")
## Add optional arguments
parser.add_argument("-n", "--name", default="World", help="The name to greet (default: World)")
parser.add_argument("-g", "--greeting", default="Hello", help="The greeting to use (default: Hello)")
parser.add_argument("-c", "--count", type=int, default=1, help="Number of times to display the greeting (default: 1)")
parser.add_argument("-u", "--uppercase", action="store_true", help="Display the greeting in uppercase")
## Parse the arguments
args = parser.parse_args()
## Create the greeting message
message = f"{args.greeting}, {args.name}!"
## Convert to uppercase if requested
if args.uppercase:
message = message.upper()
## Display the greeting
for _ in range(args.count):
print(message)
-
Save the file.
-
Run the program with the uppercase flag:
python /home/labex/project/greeting.py -n Charlie -u
- You should see the greeting in uppercase:
HELLO, CHARLIE!
The action="store_true"
parameter means the flag does not take a value - it is either present (True) or absent (False).
Optional arguments make your command-line interfaces more flexible and user-friendly. They allow users to customize the behavior of your program without requiring them to provide every piece of information every time.
In the next step, we will see how to combine positional and optional arguments in a single program.