Argparse optional positional arguments?
In Python, the argparse module can be used to specify optional positional arguments by setting the nargs parameter to '?'.
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:
Argparse optional positional arguments in a Python script
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)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
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