Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -442,9 +442,8 @@ is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.

.. note::

Empty lines are treated as empty strings (``''``), which are allowed as values but
not as arguments. Empty lines that are read as arguments will result in an
"unrecognized arguments" error.
Each line is treated as a single argument, so an empty line is read as an
empty string (``''``).
Comment on lines +445 to +446

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to simulate the situation where empty strings are passed from a file and it doesn't return an unrecognized argument, so this note makes much more sense to me and is perfectly understandable.

I also tried to simulate the unrecognized arguments error to see when it appears and my understanding is that it's related to leftover tokens in general rather than empty strings. So, if my understanding is correct, it also makes sense that it was removed here.

So, overall, the new wording is much clearer to me.

>>> import argparse
>>> with open("args.txt", "w") as f:
...   f.write("-f\n\nbar\n")
...
8
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
>>> parser.add_argument("-f")
_StoreAction(option_strings=['-f'], dest='f', nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None, deprecated=False)
>>> parser.add_argument("rest", nargs="*")
_StoreAction(option_strings=[], dest='rest', nargs='*', const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None, deprecated=False)
>>> parser._read_args_from_files(["@args.txt"])
['-f', '', 'bar']
>>> parser.parse_args(["@args.txt"])
Namespace(f='', rest=['bar'])
>>> p2 = argparse.ArgumentParser(fromfile_prefix_chars="@")
>>> p2.add_argument("-f")
_StoreAction(option_strings=['-f'], dest='f', nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None, deprecated=False)
>>> p2.parse_args(["@args.txt"])
usage: [-h] [-f F]
: error: unrecognized arguments: bar


:class:`ArgumentParser` uses :term:`filesystem encoding and error handler`
to read the file containing arguments.
Expand Down Expand Up @@ -2232,6 +2231,9 @@ Customizing file parsing
def convert_arg_line_to_args(self, arg_line):
return arg_line.split()

Note that with this override an argument can no longer contain spaces, since
each space-separated word becomes a separate argument.


Exiting methods
^^^^^^^^^^^^^^^
Expand Down
Loading