Skip to content

Commit 208f03c

Browse files
committed
pythongh-85308: argparse: Use filesystem encoding for arguments file
1 parent 88f0d0c commit 208f03c

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

Doc/library/argparse.rst

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -562,7 +562,7 @@ at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
562562
specified characters will be treated as files, and will be replaced by the
563563
arguments they contain. For example::
564564

565-
>>> with open('args.txt', 'w') as fp:
565+
>>> with open('args.txt', 'w', encoding=sys.getfilesystemencoding()) as fp:
566566
... fp.write('-f\nbar')
567567
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
568568
>>> parser.add_argument('-f')
@@ -575,9 +575,19 @@ were in the same place as the original file referencing argument on the command
575575
line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
576576
is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
577577

578+
:class:`ArgumentParser` uses :term:`filesystem encoding and error handler`
579+
to read the file containing arguments.
580+
578581
The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
579582
arguments will never be treated as file references.
580583

584+
.. versionchanged:: 3.12
585+
:class:`ArgumentParser` changed encoding and errors to read arguments files
586+
from default text encoding (e.g. :func:`locale.getpreferredencoding(False)`
587+
and `"strict"`) to :term:`filesystem encoding and error handler`.
588+
This change affects Windows; argument file should be encoded with UTF-8
589+
instead of ANSI Codepage.
590+
581591

582592
argument_default
583593
^^^^^^^^^^^^^^^^

Lib/argparse.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2161,7 +2161,9 @@ def _read_args_from_files(self, arg_strings):
21612161
# replace arguments referencing files with the file content
21622162
else:
21632163
try:
2164-
with open(arg_string[1:]) as args_file:
2164+
with open(arg_string[1:],
2165+
encoding=_sys.getfilesystemencoding(),
2166+
errors=_sys.getfilesystemencodeerrors()) as args_file:
21652167
arg_strings = []
21662168
for arg_line in args_file.read().splitlines():
21672169
for arg in self.convert_arg_line_to_args(arg_line):
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Changed :class:`argparse.ArgumentParser` to use :term:`filesystem encoding
2+
and error handler` instead of default text encoding to read arguments from
3+
file (e.g. ``fromfile_prefix_chars`` option). This change affects Windows;
4+
argument file should be encoded with UTF-8 instead of ANSI Codepage.

0 commit comments

Comments
 (0)