From 435b8778581b1dc4f81b60d9ff9e453467b6d8e8 Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 09:44:47 +0100 Subject: [PATCH 01/13] shlex: Support parsing byte streams for posix=False or whitespace_split=True --- Lib/shlex.py | 132 ++++++++++++++++++++++++++--------------- Lib/test/test_shlex.py | 22 ++++++- 2 files changed, 102 insertions(+), 52 deletions(-) diff --git a/Lib/shlex.py b/Lib/shlex.py index c7ffc918d53961..a50774ec5e6c1b 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -8,7 +8,7 @@ # changes to tokenize more like Posix shells by Vinay Sajip, July 2016. import sys -from io import StringIO +from io import StringIO, BytesIO __all__ = ["shlex", "split", "quote", "join"] @@ -20,48 +20,63 @@ def __init__(self, instream=None, infile=None, posix=False, if isinstance(instream, str): instream = StringIO(instream) + if isinstance(instream, bytes): + instream = BytesIO(instream) if instream is not None: self.instream = instream self.infile = infile else: self.instream = sys.stdin self.infile = None + self.binary = isinstance(self.instream.read(0), bytes) + self.empty = b'' if self.binary else '' self.posix = posix if posix: self.eof = None else: - self.eof = '' - self.commenters = '#' - self.wordchars = ('abcdfeghijklmnopqrstuvwxyz' + self.eof = self.empty + self.commenters = b'#' if self.binary else '#' + self.wordchars = (b'abcdfeghijklmnopqrstuvwxyz' + b'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' + if self.binary else + 'abcdfeghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_') if self.posix: self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ') - self.whitespace = ' \t\r\n' + self.whitespace = b' \t\r\n' if self.binary else ' \t\r\n' self.whitespace_split = False - self.quotes = '\'"' - self.escape = '\\' - self.escapedquotes = '"' - self.state = ' ' + self.quotes = b'\'"' if self.binary else '\'"' + self.escape = b'\\' if self.binary else '\\' + self.escapedquotes = b'"' if self.binary else '"' + self.includequote = self.escapedquotes + self.space = b' ' if self.binary else ' ' + self.A = b'a' if self.binary else 'a' + self.C = b'c' if self.binary else 'c' + self.state = self.space self.pushback = deque() self.lineno = 1 self.debug = 0 - self.token = '' + self.token = self.empty + self.newline = b'\n' if self.binary else '\n' self.filestack = deque() self.source = None if not punctuation_chars: - punctuation_chars = '' + punctuation_chars = self.empty elif punctuation_chars is True: - punctuation_chars = '();<>|&' + punctuation_chars = b'();<>|&' if self.binary else '();<>|&' self._punctuation_chars = punctuation_chars if punctuation_chars: # _pushback_chars is a push back queue used by lookahead logic self._pushback_chars = deque() # these chars added because allowed in file names, args, wildcards - self.wordchars += '~-./*?=' + self.wordchars += b'~-./*?=' if self.binary else '~-./*?=' #remove any punctuation chars from wordchars - t = self.wordchars.maketrans(dict.fromkeys(punctuation_chars)) - self.wordchars = self.wordchars.translate(t) + if self.binary: + self.wordchars = self.wordchars.translate(None, delete = punctuation_chars) + else: + t = self.wordchars.maketrans(dict.fromkeys(punctuation_chars)) + self.wordchars = self.wordchars.translate(t) @property def punctuation_chars(self): @@ -77,6 +92,11 @@ def push_source(self, newstream, newfile=None): "Push an input source onto the lexer's input source stack." if isinstance(newstream, str): newstream = StringIO(newstream) + if isinstance(newstream, bytes): + newstream = BytesIO(newstream) + binary = isinstance(newstream.read(0), bytes) + if binary != self.binary: + raise TypeError("Cannot append %s to %s" % (type(self.instream).__name__, type(newstream).__name__)) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream @@ -94,7 +114,7 @@ def pop_source(self): if self.debug: print('shlex: popping to %s, line %d' \ % (self.instream, self.lineno)) - self.state = ' ' + self.state = self.space def get_token(self): "Get a token from the input stream (or from stack if it's nonempty)" @@ -129,24 +149,26 @@ def get_token(self): return raw def read_token(self): + if self.posix and self.binary and not self.whitespace_split: + raise ValueError('POSIX word characters not supported with byte streams') quoted = False - escapedstate = ' ' + escapedstate = self.space while True: if self.punctuation_chars and self._pushback_chars: nextchar = self._pushback_chars.pop() else: nextchar = self.instream.read(1) - if nextchar == '\n': + if nextchar == self.newline: self.lineno += 1 if self.debug >= 3: print("shlex: in state %r I see character: %r" % (self.state, nextchar)) if self.state is None: - self.token = '' # past end of file + self.token = self.empty # past end of file break - elif self.state == ' ': + elif self.state == self.space: if not nextchar: - self.state = None # end of file + self.state = None # end of file break elif nextchar in self.whitespace: if self.debug >= 2: @@ -159,21 +181,21 @@ def read_token(self): self.instream.readline() self.lineno += 1 elif self.posix and nextchar in self.escape: - escapedstate = 'a' + escapedstate = self.A self.state = nextchar elif nextchar in self.wordchars: self.token = nextchar - self.state = 'a' + self.state = self.A elif nextchar in self.punctuation_chars: self.token = nextchar - self.state = 'c' + self.state = self.C elif nextchar in self.quotes: if not self.posix: self.token = nextchar self.state = nextchar elif self.whitespace_split: self.token = nextchar - self.state = 'a' + self.state = self.A else: self.token = nextchar if self.token or (self.posix and quoted): @@ -190,10 +212,10 @@ def read_token(self): if nextchar == self.state: if not self.posix: self.token += nextchar - self.state = ' ' + self.state = self.space break else: - self.state = 'a' + self.state = self.A elif (self.posix and nextchar in self.escape and self.state in self.escapedquotes): escapedstate = self.state @@ -213,14 +235,14 @@ def read_token(self): self.token += self.state self.token += nextchar self.state = escapedstate - elif self.state in ('a', 'c'): + elif self.state in (self.A, self.C): if not nextchar: self.state = None # end of file break elif nextchar in self.whitespace: if self.debug >= 2: print("shlex: I see whitespace in word state") - self.state = ' ' + self.state = self.space if self.token or (self.posix and quoted): break # emit current token else: @@ -229,23 +251,23 @@ def read_token(self): self.instream.readline() self.lineno += 1 if self.posix: - self.state = ' ' + self.state = self.space if self.token or (self.posix and quoted): break # emit current token else: continue - elif self.state == 'c': + elif self.state == self.C: if nextchar in self.punctuation_chars: self.token += nextchar else: if nextchar not in self.whitespace: self._pushback_chars.append(nextchar) - self.state = ' ' + self.state = self.space break elif self.posix and nextchar in self.quotes: self.state = nextchar elif self.posix and nextchar in self.escape: - escapedstate = 'a' + escapedstate = self.A self.state = nextchar elif (nextchar in self.wordchars or nextchar in self.quotes or (self.whitespace_split and @@ -258,14 +280,14 @@ def read_token(self): self.pushback.appendleft(nextchar) if self.debug >= 2: print("shlex: I see punctuation in word state") - self.state = ' ' + self.state = self.space if self.token or (self.posix and quoted): break # emit current token else: continue result = self.token - self.token = '' - if self.posix and not quoted and result == '': + self.token = self.empty + if self.posix and not quoted and result == self.empty: result = None if self.debug > 1: if result: @@ -277,12 +299,18 @@ def read_token(self): def sourcehook(self, newfile): "Hook called on a filename to be sourced." import os.path - if newfile[0] == '"': + if newfile[0] == self.includequote: newfile = newfile[1:-1] + infile = self.infile # This implements cpp-like semantics for relative-path inclusion. - if isinstance(self.infile, str) and not os.path.isabs(newfile): - newfile = os.path.join(os.path.dirname(self.infile), newfile) - return (newfile, open(newfile, "r")) + if (isinstance(infile, str) or isinstance(infile, bytes)) and not os.path.isabs(newfile): + if isinstance(infile, bytes) != isinstance(newfile, bytes): + if not isinstance(infile, bytes): + infile = infile.encode() + else: + newfile = newfile.encode() + newfile = os.path.join(os.path.dirname(infile), newfile) + return (newfile, open(newfile, 'rb' if self.binary else 'r')) def error_leader(self, infile=None, lineno=None): "Emit a C-compiler-like, Emacs-friendly error-message leader." @@ -290,7 +318,7 @@ def error_leader(self, infile=None, lineno=None): infile = self.infile if lineno is None: lineno = self.lineno - return "\"%s\", line %d: " % (infile, lineno) + return "%r, line %d: " % (infile, lineno) def __iter__(self): return self @@ -302,19 +330,21 @@ def __next__(self): return token def split(s, comments=False, posix=True): - """Split the string *s* using shell-like syntax.""" + """Split the string or byte array *s* using shell-like syntax.""" if s is None: raise ValueError("s argument must not be None") lex = shlex(s, posix=posix) lex.whitespace_split = True if not comments: - lex.commenters = '' + lex.commenters = lex.empty return list(lex) def join(split_command): """Return a shell-escaped string from *split_command*.""" - return ' '.join(quote(arg) for arg in split_command) + split_command = list(split_command) + space = b' ' if split_command and isinstance(split_command[0], bytes) else ' ' + return space.join(quote(arg) for arg in split_command) def quote(s, *, force=False): @@ -323,11 +353,12 @@ def quote(s, *, force=False): If *force* is *True*, then *s* is unconditionally quoted, even if it is already safe for a shell without being quoted. """ + is_bytes = isinstance(s, bytes) if not s: - return "''" + return b"''" if is_bytes else "''" - if not isinstance(s, str): - raise TypeError(f"expected string object, got {type(s).__name__!r}") + if not isinstance(s, str) and not isinstance(s, bytes): + raise TypeError(f"expected string or byte array object, got {type(s).__name__!r}") # Use bytes.translate() for performance safe_chars = (b'%+,-./0123456789:=@' @@ -336,12 +367,15 @@ def quote(s, *, force=False): # No quoting is needed if we are not forcing quoting # and `s` is an ASCII string consisting only of `safe_chars`. if (not force - and s.isascii() and not s.encode().translate(None, delete=safe_chars)): + and s.isascii() and + not (s if is_bytes else s.encode()).translate(None, delete=safe_chars)): return s # use single quotes, and put single quotes into double quotes # the string $'b is then quoted as '$'"'"'b' - return "'" + s.replace("'", "'\"'\"'") + "'" + quote = b"'" if is_bytes else "'" + replace = b"'\"'\"'" if is_bytes else "'\"'\"'" + return quote + s.replace(quote, replace) + quote def _print_tokens(lexer): diff --git a/Lib/test/test_shlex.py b/Lib/test/test_shlex.py index 4c0cd88bbcda14..60105bde9cf037 100644 --- a/Lib/test/test_shlex.py +++ b/Lib/test/test_shlex.py @@ -294,6 +294,18 @@ def testPunctuationWithWhitespaceSplit(self): # white space self.assertEqual(list(s), ['a', '&&', 'b', '||', 'c']) + def testPunctuationWithWhitespaceSplitBytes(self): + """Test that with whitespace_split, behaviour is as expected with bytes""" + s = shlex.shlex(b'a && b || c', punctuation_chars=b'&') + # whitespace_split is False, so splitting will be based on + # punctuation_chars + self.assertEqual(list(s), [b'a', b'&&', b'b', b'|', b'|', b'c']) + s = shlex.shlex(b'a && b || c', punctuation_chars=b'&') + s.whitespace_split = True + # whitespace_split is True, so splitting will be based on + # white space + self.assertEqual(list(s), [b'a', b'&&', b'b', b'||', b'c']) + def testPunctuationWithPosix(self): """Test that punctuation_chars and posix behave correctly together.""" # see Issue #29132 @@ -333,17 +345,21 @@ def testQuote(self): unsafe = '"`$\\!' + unicode_sample self.assertEqual(shlex.quote(''), "''") + self.assertEqual(shlex.quote(b''), b"''") self.assertEqual(shlex.quote(None), "''") self.assertEqual(shlex.quote(safeunquoted), safeunquoted) + self.assertEqual(shlex.quote(safeunquoted.encode()), safeunquoted.encode()) self.assertEqual(shlex.quote('test file name'), "'test file name'") + self.assertEqual(shlex.quote(b'test file name'), b"'test file name'") for u in unsafe: self.assertEqual(shlex.quote('test%sname' % u), "'test%sname'" % u) + self.assertEqual(shlex.quote(b'test%sname' % u.encode()), + b"'test%sname'" % u.encode()) for u in unsafe: self.assertEqual(shlex.quote("test%s'name'" % u), "'test%s'\"'\"'name'\"'\"''" % u) self.assertRaises(TypeError, shlex.quote, 42) - self.assertRaises(TypeError, shlex.quote, b"abc") def testForceQuote(self): self.assertEqual(shlex.quote("spam"), "spam") @@ -457,14 +473,14 @@ def testErrorLeaderTracksPosition(self): s = shlex.shlex("line 1\nline 2", infile=infile_label) list(s) result = s.error_leader() - self.assertEqual(result, f'"{infile_label}", line 2: ') + self.assertEqual(result, f"'{infile_label}', line 2: ") def testErrorLeaderOverrides(self): s = shlex.shlex("foo", infile="original.sh") infile_label_override = "override.sh" lineno_override = 42 result = s.error_leader(infile=infile_label_override, lineno=lineno_override) - self.assertEqual(result, f'"{infile_label_override}", line {lineno_override}: ') + self.assertEqual(result, f"'{infile_label_override}', line {lineno_override}: ") def testNoClosingQuotation(self): s = shlex.shlex('"foo') From 75501d93c8f370defe19c4aa3de7290899fa2cf0 Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 12:37:53 +0100 Subject: [PATCH 02/13] Add NEWS entry --- .../next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst diff --git a/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst new file mode 100644 index 00000000000000..dc28baeb70a0b4 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst @@ -0,0 +1,3 @@ +Support shlex parsing byte streams for posix=False or whitespace_split=True. +Removes the annoying limitation that byte arrays are not supported by shlex. +Unlike python shlex actual shells use byte arrays, not python strings. From d2a3a91c1389521f0920b8d5890609fc0bfed435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Such=C3=A1nek?= Date: Fri, 4 Dec 2026 17:19:12 +0000 Subject: [PATCH 03/13] Update Lib/shlex.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> --- Lib/shlex.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/shlex.py b/Lib/shlex.py index a50774ec5e6c1b..12ba8d66a24956 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -73,7 +73,7 @@ def __init__(self, instream=None, infile=None, posix=False, self.wordchars += b'~-./*?=' if self.binary else '~-./*?=' #remove any punctuation chars from wordchars if self.binary: - self.wordchars = self.wordchars.translate(None, delete = punctuation_chars) + self.wordchars = self.wordchars.translate(None, delete=punctuation_chars) else: t = self.wordchars.maketrans(dict.fromkeys(punctuation_chars)) self.wordchars = self.wordchars.translate(t) From 3fc672727eb9ee262ebe0a4406792b75591ad065 Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 18:34:34 +0100 Subject: [PATCH 04/13] Fixup: Addressing some review comments --- Lib/shlex.py | 12 ++++++------ .../2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst | 3 +-- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/Lib/shlex.py b/Lib/shlex.py index 12ba8d66a24956..aa76d3273add0c 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -20,7 +20,7 @@ def __init__(self, instream=None, infile=None, posix=False, if isinstance(instream, str): instream = StringIO(instream) - if isinstance(instream, bytes): + elif isinstance(instream, bytes): instream = BytesIO(instream) if instream is not None: self.instream = instream @@ -92,7 +92,7 @@ def push_source(self, newstream, newfile=None): "Push an input source onto the lexer's input source stack." if isinstance(newstream, str): newstream = StringIO(newstream) - if isinstance(newstream, bytes): + elif isinstance(newstream, bytes): newstream = BytesIO(newstream) binary = isinstance(newstream.read(0), bytes) if binary != self.binary: @@ -168,7 +168,7 @@ def read_token(self): break elif self.state == self.space: if not nextchar: - self.state = None # end of file + self.state = None # end of file break elif nextchar in self.whitespace: if self.debug >= 2: @@ -330,7 +330,7 @@ def __next__(self): return token def split(s, comments=False, posix=True): - """Split the string or byte array *s* using shell-like syntax.""" + """Split the string or byte-like object *s* using shell-like syntax.""" if s is None: raise ValueError("s argument must not be None") lex = shlex(s, posix=posix) @@ -357,8 +357,8 @@ def quote(s, *, force=False): if not s: return b"''" if is_bytes else "''" - if not isinstance(s, str) and not isinstance(s, bytes): - raise TypeError(f"expected string or byte array object, got {type(s).__name__!r}") + if not isinstance(s, str) and not is_bytes: + raise TypeError(f"expected string or bytes object, got {type(s).__name__!r}") # Use bytes.translate() for performance safe_chars = (b'%+,-./0123456789:=@' diff --git a/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst index dc28baeb70a0b4..2034b97889c02d 100644 --- a/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst +++ b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst @@ -1,3 +1,2 @@ Support shlex parsing byte streams for posix=False or whitespace_split=True. -Removes the annoying limitation that byte arrays are not supported by shlex. -Unlike python shlex actual shells use byte arrays, not python strings. +Removes the limitation that byte arrays are not supported by shlex. From edebd81e9a04d904e6a4048d43bfaae38468bde5 Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 18:44:13 +0100 Subject: [PATCH 05/13] Update shlex.rst as well --- Doc/library/shlex.rst | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/Doc/library/shlex.rst b/Doc/library/shlex.rst index 1065dc0a4e5fb1..822ccf1b0dc152 100644 --- a/Doc/library/shlex.rst +++ b/Doc/library/shlex.rst @@ -18,17 +18,20 @@ The :mod:`!shlex` module defines the following functions: .. function:: split(s, comments=False, posix=True) - Split the string *s* using shell-like syntax. If *comments* is :const:`False` - (the default), the parsing of comments in the given string will be disabled - (setting the :attr:`~shlex.commenters` attribute of the - :class:`~shlex.shlex` instance to the empty string). This function operates - in POSIX mode by default, but uses non-POSIX mode if the *posix* argument is - false. + Split the string or byte-like object *s* using shell-like syntax. If + *comments* is :const:`False` (the default), the parsing of comments in the + given string will be disabled (setting the :attr:`~shlex.commenters` + attribute of the :class:`~shlex.shlex` instance to the empty string). This + function operates in POSIX mode by default, but uses non-POSIX mode if the + *posix* argument is false. .. versionchanged:: 3.12 Passing ``None`` for *s* argument now raises an exception, rather than reading :data:`sys.stdin`. + .. versionchanged:: 3.16 + Support byte-like object as input. + .. function:: join(split_command) Concatenate the tokens of the list *split_command* and return a string. @@ -43,12 +46,15 @@ The :mod:`!shlex` module defines the following functions: .. versionadded:: 3.8 + .. versionchanged:: 3.16 + Support sequence of byte-like objects as input. + .. function:: quote(s, *, force=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. + Return a shell-escaped version of the string or byte-like object *s*. The + returned value is a string or bytes object that can safely be used as one + token in a shell command line, for cases where you cannot use a list. If *force* is :const:`True`, then *s* is unconditionally quoted, even if it is already safe for a shell without being quoted. @@ -110,6 +116,7 @@ The :mod:`!shlex` module defines the following functions: .. versionchanged:: 3.16 The *force* keyword was added. + Support byte-like object as input. The :mod:`!shlex` module defines the following class: @@ -144,6 +151,9 @@ The :mod:`!shlex` module defines the following class: .. versionchanged:: 3.6 The *punctuation_chars* parameter was added. + .. versionchanged:: 3.16 + Support byte-like object or binary IO as *instream*. + .. seealso:: Module :mod:`configparser` From 619fa0f090635f59eaafcec7c0aa2bca46dc59ad Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 18:46:46 +0100 Subject: [PATCH 06/13] Order imports --- Lib/shlex.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/shlex.py b/Lib/shlex.py index aa76d3273add0c..3ef529c41a15a9 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -8,7 +8,7 @@ # changes to tokenize more like Posix shells by Vinay Sajip, July 2016. import sys -from io import StringIO, BytesIO +from io import BytesIO, StringIO __all__ = ["shlex", "split", "quote", "join"] From 65e36ae2317ed55a36199244314961c328070091 Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 18:54:34 +0100 Subject: [PATCH 07/13] Change binary input detection --- Lib/shlex.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/shlex.py b/Lib/shlex.py index 3ef529c41a15a9..abafebb99f58e6 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -8,7 +8,7 @@ # changes to tokenize more like Posix shells by Vinay Sajip, July 2016. import sys -from io import BytesIO, StringIO +from io import BytesIO, TextIOBase, StringIO __all__ = ["shlex", "split", "quote", "join"] @@ -28,7 +28,7 @@ def __init__(self, instream=None, infile=None, posix=False, else: self.instream = sys.stdin self.infile = None - self.binary = isinstance(self.instream.read(0), bytes) + self.binary = not isinstance(self.instream, TextIOBase) self.empty = b'' if self.binary else '' self.posix = posix if posix: From c25e7d614124e1e64a9ea88d21dae0e163fa2d4e Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 19:02:13 +0100 Subject: [PATCH 08/13] byte-like object -> bytes --- Doc/library/shlex.rst | 26 +++++++++++++------------- Lib/shlex.py | 6 +++--- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Doc/library/shlex.rst b/Doc/library/shlex.rst index 822ccf1b0dc152..56240f54f91c02 100644 --- a/Doc/library/shlex.rst +++ b/Doc/library/shlex.rst @@ -18,19 +18,19 @@ The :mod:`!shlex` module defines the following functions: .. function:: split(s, comments=False, posix=True) - Split the string or byte-like object *s* using shell-like syntax. If - *comments* is :const:`False` (the default), the parsing of comments in the - given string will be disabled (setting the :attr:`~shlex.commenters` - attribute of the :class:`~shlex.shlex` instance to the empty string). This - function operates in POSIX mode by default, but uses non-POSIX mode if the - *posix* argument is false. + Split the string or bytes *s* using shell-like syntax. If *comments* is + :const:`False` (the default), the parsing of comments in the given string + will be disabled (setting the :attr:`~shlex.commenters` attribute of the + :class:`~shlex.shlex` instance to the empty string). This function operates + in POSIX mode by default, but uses non-POSIX mode if the *posix* argument is + false. .. versionchanged:: 3.12 Passing ``None`` for *s* argument now raises an exception, rather than reading :data:`sys.stdin`. .. versionchanged:: 3.16 - Support byte-like object as input. + Support bytes as input. .. function:: join(split_command) @@ -47,14 +47,14 @@ The :mod:`!shlex` module defines the following functions: .. versionadded:: 3.8 .. versionchanged:: 3.16 - Support sequence of byte-like objects as input. + Support sequence of bytes as input. .. function:: quote(s, *, force=False) - Return a shell-escaped version of the string or byte-like object *s*. The - returned value is a string or bytes object that can safely be used as one - token in a shell command line, for cases where you cannot use a list. + Return a shell-escaped version of the string or bytes *s*. The returned + value is a string or bytes object that can safely be used as one token in a + shell command line, for cases where you cannot use a list. If *force* is :const:`True`, then *s* is unconditionally quoted, even if it is already safe for a shell without being quoted. @@ -116,7 +116,7 @@ The :mod:`!shlex` module defines the following functions: .. versionchanged:: 3.16 The *force* keyword was added. - Support byte-like object as input. + Support bytes as input. The :mod:`!shlex` module defines the following class: @@ -152,7 +152,7 @@ The :mod:`!shlex` module defines the following class: The *punctuation_chars* parameter was added. .. versionchanged:: 3.16 - Support byte-like object or binary IO as *instream*. + Support bytes or binary IO as *instream*. .. seealso:: diff --git a/Lib/shlex.py b/Lib/shlex.py index abafebb99f58e6..f29bd49d2692fb 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -330,7 +330,7 @@ def __next__(self): return token def split(s, comments=False, posix=True): - """Split the string or byte-like object *s* using shell-like syntax.""" + """Split the string or bytes *s* using shell-like syntax.""" if s is None: raise ValueError("s argument must not be None") lex = shlex(s, posix=posix) @@ -341,14 +341,14 @@ def split(s, comments=False, posix=True): def join(split_command): - """Return a shell-escaped string from *split_command*.""" + """Return a shell-escaped string or bytes from *split_command*.""" split_command = list(split_command) space = b' ' if split_command and isinstance(split_command[0], bytes) else ' ' return space.join(quote(arg) for arg in split_command) def quote(s, *, force=False): - """Return a shell-escaped version of the string *s*. + """Return a shell-escaped version of the string or bytes *s*. If *force* is *True*, then *s* is unconditionally quoted, even if it is already safe for a shell without being quoted. From a1761d247ffca1ac374e0bff5f75df4df7751d0b Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 19:05:04 +0100 Subject: [PATCH 09/13] self.{A,C} -> self.lit_{a,c} --- Lib/shlex.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Lib/shlex.py b/Lib/shlex.py index f29bd49d2692fb..3a243ba64562da 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -51,8 +51,8 @@ def __init__(self, instream=None, infile=None, posix=False, self.escapedquotes = b'"' if self.binary else '"' self.includequote = self.escapedquotes self.space = b' ' if self.binary else ' ' - self.A = b'a' if self.binary else 'a' - self.C = b'c' if self.binary else 'c' + self.lit_a = b'a' if self.binary else 'a' + self.lit_c = b'c' if self.binary else 'c' self.state = self.space self.pushback = deque() self.lineno = 1 @@ -181,21 +181,21 @@ def read_token(self): self.instream.readline() self.lineno += 1 elif self.posix and nextchar in self.escape: - escapedstate = self.A + escapedstate = self.lit_a self.state = nextchar elif nextchar in self.wordchars: self.token = nextchar - self.state = self.A + self.state = self.lit_a elif nextchar in self.punctuation_chars: self.token = nextchar - self.state = self.C + self.state = self.lit_c elif nextchar in self.quotes: if not self.posix: self.token = nextchar self.state = nextchar elif self.whitespace_split: self.token = nextchar - self.state = self.A + self.state = self.lit_a else: self.token = nextchar if self.token or (self.posix and quoted): @@ -215,7 +215,7 @@ def read_token(self): self.state = self.space break else: - self.state = self.A + self.state = self.lit_a elif (self.posix and nextchar in self.escape and self.state in self.escapedquotes): escapedstate = self.state @@ -235,7 +235,7 @@ def read_token(self): self.token += self.state self.token += nextchar self.state = escapedstate - elif self.state in (self.A, self.C): + elif self.state in (self.lit_a, self.lit_c): if not nextchar: self.state = None # end of file break @@ -256,7 +256,7 @@ def read_token(self): break # emit current token else: continue - elif self.state == self.C: + elif self.state == self.lit_c: if nextchar in self.punctuation_chars: self.token += nextchar else: @@ -267,7 +267,7 @@ def read_token(self): elif self.posix and nextchar in self.quotes: self.state = nextchar elif self.posix and nextchar in self.escape: - escapedstate = self.A + escapedstate = self.lit_a self.state = nextchar elif (nextchar in self.wordchars or nextchar in self.quotes or (self.whitespace_split and From d37f4431aa84a8083b2940921d85699782cac2b8 Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 19:14:19 +0100 Subject: [PATCH 10/13] Update NEWS again --- .../next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst index 2034b97889c02d..22954fc7a7e04d 100644 --- a/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst +++ b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst @@ -1,2 +1,2 @@ Support shlex parsing byte streams for posix=False or whitespace_split=True. -Removes the limitation that byte arrays are not supported by shlex. +Removes the limitation that bytes are not supported by shlex split/quote. From 50ea8281bd510f92b249209ccd2a7dfec6f4cb0f Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 19:24:27 +0100 Subject: [PATCH 11/13] Another update to docs - linkify NEWS - the shlex class description should also mention bytes --- Doc/library/shlex.rst | 3 ++- .../Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Doc/library/shlex.rst b/Doc/library/shlex.rst index 56240f54f91c02..41adf3e31a7528 100644 --- a/Doc/library/shlex.rst +++ b/Doc/library/shlex.rst @@ -127,7 +127,8 @@ The :mod:`!shlex` module defines the following class: object. The initialization argument, if present, specifies where to read characters from. It must be a file-/stream-like object with :meth:`~io.TextIOBase.read` and :meth:`~io.TextIOBase.readline` methods, or - a string. If no argument is given, input will be taken from ``sys.stdin``. + a string or a file-like object or bytes. If no argument is given, input + will be taken from ``sys.stdin``. The second optional argument is a filename string, which sets the initial value of the :attr:`~shlex.infile` attribute. If the *instream* argument is omitted or equal to ``sys.stdin``, this second argument diff --git a/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst index 22954fc7a7e04d..19033c1929a7e8 100644 --- a/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst +++ b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst @@ -1,2 +1,2 @@ -Support shlex parsing byte streams for posix=False or whitespace_split=True. -Removes the limitation that bytes are not supported by shlex split/quote. +Support :class:`~shlex.shlex` parsing byte streams for posix=False or whitespace_split=True. +Removes the limitation that bytes are not supported by shlex :func:`quote` and :func:`split`. From 745f2ee13074b5baaa60049188c1f9f3a8e508f2 Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 19:36:23 +0100 Subject: [PATCH 12/13] Fix links in NEWS --- .../next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst index 19033c1929a7e8..17c62daa985763 100644 --- a/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst +++ b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst @@ -1,2 +1,2 @@ Support :class:`~shlex.shlex` parsing byte streams for posix=False or whitespace_split=True. -Removes the limitation that bytes are not supported by shlex :func:`quote` and :func:`split`. +Removes the limitation that bytes are not supported by shlex :func:`~shlex.quote` and :func:`~shlex.split`. From 260ba82503c861545f797f44cff60babcdec6d0f Mon Sep 17 00:00:00 2001 From: Michal Suchanek Date: Fri, 4 Dec 2026 20:03:56 +0100 Subject: [PATCH 13/13] Revert the error format change --- Lib/shlex.py | 5 ++++- Lib/test/test_shlex.py | 13 +++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Lib/shlex.py b/Lib/shlex.py index 3a243ba64562da..d3e9a25a22be88 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -312,13 +312,16 @@ def sourcehook(self, newfile): newfile = os.path.join(os.path.dirname(infile), newfile) return (newfile, open(newfile, 'rb' if self.binary else 'r')) + def _to_str(self, s): + return s.decode(errors='replace') if isinstance(s, bytes) else s + def error_leader(self, infile=None, lineno=None): "Emit a C-compiler-like, Emacs-friendly error-message leader." if infile is None: infile = self.infile if lineno is None: lineno = self.lineno - return "%r, line %d: " % (infile, lineno) + return '"%s", line %d: ' % (self._to_str(infile), lineno) def __iter__(self): return self diff --git a/Lib/test/test_shlex.py b/Lib/test/test_shlex.py index 60105bde9cf037..57d324c214a1b4 100644 --- a/Lib/test/test_shlex.py +++ b/Lib/test/test_shlex.py @@ -473,14 +473,23 @@ def testErrorLeaderTracksPosition(self): s = shlex.shlex("line 1\nline 2", infile=infile_label) list(s) result = s.error_leader() - self.assertEqual(result, f"'{infile_label}', line 2: ") + self.assertEqual(result, f'"{infile_label}", line 2: ') + + def testErrorLeaderTracksPositionBytes(self): + infile_label = "test.sh" + s = shlex.shlex("line 1\nline 2", infile=infile_label.encode()) + list(s) + result = s.error_leader() + self.assertEqual(result, f'"{infile_label}", line 2: ') def testErrorLeaderOverrides(self): s = shlex.shlex("foo", infile="original.sh") infile_label_override = "override.sh" lineno_override = 42 result = s.error_leader(infile=infile_label_override, lineno=lineno_override) - self.assertEqual(result, f"'{infile_label_override}', line {lineno_override}: ") + self.assertEqual(result, f'"{infile_label_override}", line {lineno_override}: ') + result = s.error_leader(infile=infile_label_override.encode(), lineno=lineno_override) + self.assertEqual(result, f'"{infile_label_override}", line {lineno_override}: ') def testNoClosingQuotation(self): s = shlex.shlex('"foo')