#11175: argparse.FileType now accepts encoding and errors arguments.

Patch by Lucas Maystre.
This commit is contained in:
Petri Lehtinen 2012-12-15 22:39:32 +02:00
parent 09bb89b8cf
commit 74d6c250e1
5 changed files with 60 additions and 12 deletions

View file

@ -976,9 +976,9 @@ See the section on the default_ keyword argument for information on when the
``type`` argument is applied to default arguments.
To ease the use of various types of files, the argparse module provides the
factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
:func:`open` function. For example, ``FileType('w')`` can be used to create a
writable file::
factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
``errors=`` arguments of the :func:`open` function. For example,
``FileType('w')`` can be used to create a writable file::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar', type=argparse.FileType('w'))
@ -1617,17 +1617,19 @@ Sub-commands
FileType objects
^^^^^^^^^^^^^^^^
.. class:: FileType(mode='r', bufsize=None)
.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
The :class:`FileType` factory creates objects that can be passed to the type
argument of :meth:`ArgumentParser.add_argument`. Arguments that have
:class:`FileType` objects as their type will open command-line arguments as files
with the requested modes and buffer sizes::
:class:`FileType` objects as their type will open command-line arguments as
files with the requested modes, buffer sizes, encodings and error handling
(see the :func:`open` function for more details)::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
>>> parser.parse_args(['--output', 'out'])
Namespace(output=<_io.BufferedWriter name='out'>)
>>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
>>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
>>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)
FileType objects understand the pseudo-argument ``'-'`` and automatically
convert this into ``sys.stdin`` for readable :class:`FileType` objects and