argumentparser close file argument

南笙酒味 提交于 2019-12-08 17:40:02

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/13736812/argumentparser-close-file-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!