Using the type
parameter of the argparse.add_argument
method, you can require an argument to be a readable file:
parser.add_argument('--sqlite-file', type=argparse.FileType('r'))
As a benefit of specifying this type, argparse checks whether the file can be read and displays an error to the user if not.
Is there a way to obtain the passed filename instead of an instance of io.TextIOWrapper
or io.BufferedReader
?
Since the filename appears in the string representation of the parser ('sqlite_file': <_io.TextIOWrapper name='data/export.sqlite' ...
, or 'sqlite_file': <_io.BufferedReader name='data/export.sqlite' ...>
) it should be possible.
How to do it?
Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.
The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.
Yes, use the .name
attribute on the file object.
Demo:
>>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--sqlite-file', type=argparse.FileType('r')) _StoreAction(option_strings=['--sqlite-file'], dest='sqlite_file', nargs=None, const=None, default=None, type=FileType('r'), choices=None, help=None, metavar=None) >>> args = parser.parse_args(['--sqlite-file', '/tmp/demo.db']) >>> args.sqlite_file <_io.TextIOWrapper name='/tmp/demo.db' mode='r' encoding='UTF-8'> >>> args.sqlite_file.name '/tmp/demo.db'
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