Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argumentparser close file argument

Tags:

python

argumentparser can take file type argument and leave the file open directly, for example:

parser.add_argument('infile', nargs='?', type=argparse.FileType('r'))
args = parser.parse_args().__dict__
input = args['infile'].readlines()

do I need to close args['infile'] in my program? Would argumentparser close it for me? I didn't find anywhere mention this in the documentations.

like image 678
Sawyer Avatar asked Dec 06 '12 04:12

Sawyer


People also ask

How do you pass arguments to Argparse?

After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() .

What command-line argument does the ArgumentParser provide by default?

Parsing arguments In a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.argv .

What does Nargs mean in Python?

nargs stands for Number Of Arguments.


2 Answers

NO, it does not close the filetype object.. see this

The problem here is that FileType may return stdin or stdout, so it can’t just always close the file object.

A great number of unclosed file handles may cause problem to some OSes, but that’s it. On the plus side, the fact that argparse accepts for its type argument any callable that can check and convert a string input is simple, clean and works.

Also look at this

like image 97
avasal Avatar answered Sep 20 '22 18:09

avasal


Some digging in the source reveals that it doesn't close it for you. That makes sense, as it also has to open files for writing, and you probably wouldn't want it to close those.

like image 40
khagler Avatar answered Sep 20 '22 18:09

khagler