Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
9 changes: 7 additions & 2 deletions Doc/library/shlex.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,13 @@ The :mod:`shlex` module defines the following functions:
.. versionadded:: 3.8


.. function:: quote(s)
.. function:: quote(s, always=False)

Return a shell-escaped version of the string *s*. The returned value is a
string that can safely be used as one token in a shell command line, for
cases where you cannot use a list.
cases where you cannot use a list. If the *always* keyword argument is
set to ``True`` then the string *s* will always be escaped, even in the
absence of special characters.

.. _shlex-quote-warning:

Expand Down Expand Up @@ -98,6 +100,9 @@ The :mod:`shlex` module defines the following functions:

.. versionadded:: 3.3

.. versionchanged:: 3.14
Added the *always* parameter.

The :mod:`shlex` module defines the following class:


Expand Down
15 changes: 6 additions & 9 deletions Lib/shlex.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,17 +320,14 @@ def join(split_command):

_find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search

def quote(s):
def quote(s, always=False):
"""Return a shell-escaped version of the string *s*."""
if not s:
return "''"
if _find_unsafe(s) is None:
return s

# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return "'" + s.replace("'", "'\"'\"'") + "'"
if always or not s or _find_unsafe(s) is not None:
# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return "'" + s.replace("'", "'\"'\"'") + "'"

return s

def _print_tokens(lexer):
while tt := lexer.get_token():
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:func:`shlex.quote` now has an *always* keyword argument for forcing
the escaping of the string passed to it
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
:func:`shlex.quote` now has an *always* keyword argument for forcing
the escaping of the string passed to it
Allow :func:`shlex.quote` to unconditionally escape its input
via the keyword-only argument *always*.