diff --git a/Doc/library/shlex.rst b/Doc/library/shlex.rst index 1065dc0a4e5fb1..41adf3e31a7528 100644 --- a/Doc/library/shlex.rst +++ b/Doc/library/shlex.rst @@ -18,9 +18,9 @@ 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 + 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. @@ -29,6 +29,9 @@ The :mod:`!shlex` module defines the following functions: Passing ``None`` for *s* argument now raises an exception, rather than reading :data:`sys.stdin`. + .. versionchanged:: 3.16 + Support bytes 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 bytes 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 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. @@ -110,6 +116,7 @@ The :mod:`!shlex` module defines the following functions: .. versionchanged:: 3.16 The *force* keyword was added. + Support bytes as input. The :mod:`!shlex` module defines the following class: @@ -120,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 @@ -144,6 +152,9 @@ The :mod:`!shlex` module defines the following class: .. versionchanged:: 3.6 The *punctuation_chars* parameter was added. + .. versionchanged:: 3.16 + Support bytes or binary IO as *instream*. + .. seealso:: Module :mod:`configparser` diff --git a/Lib/shlex.py b/Lib/shlex.py index c7ffc918d53961..d3e9a25a22be88 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 BytesIO, TextIOBase, StringIO __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) + elif 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 = not isinstance(self.instream, TextIOBase) + 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.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 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) + elif 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,22 +149,24 @@ 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 break @@ -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.lit_a self.state = nextchar elif nextchar in self.wordchars: self.token = nextchar - self.state = 'a' + self.state = self.lit_a elif nextchar in self.punctuation_chars: self.token = nextchar - self.state = '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 = 'a' + self.state = self.lit_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.lit_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.lit_a, self.lit_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.lit_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.lit_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,21 @@ 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 _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." @@ -290,7 +321,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 '"%s", line %d: ' % (self._to_str(infile), lineno) def __iter__(self): return self @@ -302,32 +333,35 @@ def __next__(self): return token def split(s, comments=False, posix=True): - """Split the string *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) 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) + """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. """ + 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 is_bytes: + raise TypeError(f"expected string or bytes object, got {type(s).__name__!r}") # Use bytes.translate() for performance safe_chars = (b'%+,-./0123456789:=@' @@ -336,12 +370,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..57d324c214a1b4 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") @@ -459,12 +475,21 @@ def testErrorLeaderTracksPosition(self): result = s.error_leader() 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}: ') + 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') 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..17c62daa985763 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-04-12-37-39.gh-issue-69753.bZdldj.rst @@ -0,0 +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:`~shlex.quote` and :func:`~shlex.split`.