Argparse optional positional arguments?
In Python, the argparse
module can be used to specify optional positional arguments by setting the nargs
parameter to '?'
. Here's an example code snippet:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input_file", nargs='?', default="default.txt")
parser.add_argument("output_file", nargs='?', default="output.txt")
args = parser.parse_args()
print(args.input_file)
print(args.output_file)
Watch a video course
Python - The Practical Guide
When you run this script, the input_file
and output_file
arguments are optional and will default to "default.txt" and "output.txt", respectively, if they are not provided.
# When you run the script with no arguments $ python script.py default.txt output.txt
# When you run the script with only one argument $ python script.py input.txt input.txt output.txt
# When you run the script with two arguments $ python script.py input.txt output.txt input.txt output.txt