I have the following helper function for parsing arguments using argparse:
def get_cli_arguments():
parser = argparse.ArgumentParser(prog='Xtrayce')
parser.add_argument(
"-o", "--output",
default=get_default_output_path(),
help="Supply an output path.",
type=argparse.FileType('wb'),
)
parser.add_argument(
"-d", "--dry",
help="Don't save a file with the output.",
action="store_true",
)
parser.add_argument(
"-s", "--standard",
help="Also scan standard library and modules.",
action="store_true",
)
I want that whenever the user specify the --dry flag, no file will be created from the --output parameter.
What is the best way to "cancel" the file creation when the user specifies --dry, while still using default= and type=argparse.FileType("wb")?
There is no easy way to do this via the default ArgumentParser as the file will be created already during the parsing of the arguments.
You can either change the type of --output to a string and add a check before writing:
parser = argparse.ArgumentParser(prog='Xtrayce')
parser.add_argument(
"-o", "--output",
default=get_default_output_path(),
help="Supply an output path.",
)
parser.add_argument(
"-d", "--dry",
help="Don't save a file with the output.",
action="store_true",
)
if not args.dry:
with open(args.output, 'wb') as f:
f.write(...)
Or instead of using a --dry parameter, you could provide - as the --output argument, which will write to sys.stdout instead of a file.
From the docs:
FileType objects understand the pseudo-argument '-' and automatically convert this into
sys.stdinfor readableFileTypeobjects andsys.stdoutfor writableFileTypeobjects:parser.add_argument('infile', type=argparse.FileType('r')) parser.parse_args(['-']) Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)```
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With