Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get filename with argparse while specifying type=FileType(...) for this argument

Tags:

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?

like image 999
jack_kerouac Avatar asked Oct 29 '13 11:10

jack_kerouac


People also ask

What does Nargs do in Argparse?

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.

What does Argparse ArgumentParser ()?

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.


1 Answers

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' 
like image 155
Martijn Pieters Avatar answered Sep 29 '22 22:09

Martijn Pieters