Add shlex.quote function, to escape filenames and command lines (#9723).

This function used to live as pipes.quote, where it was undocumented but
used anyway.  (An alias still exists for backward compatibility.)  The
tests have been moved as is, but the code of the function was changed to
use a regex instead of a loop with string comparisons (at Ian Bicking’s
suggestion).  I’m terrible at regexes, so any feedback is welcome.
This commit is contained in:
Éric Araujo 2011-07-27 18:29:31 +02:00
parent fcdaaa9011
commit 9bce311ea4
7 changed files with 66 additions and 42 deletions

View file

@ -6,13 +6,14 @@
# Posix compliance, split(), string arguments, and
# iterator interface by Gustavo Niemeyer, April 2003.
import os.path
import os
import re
import sys
from collections import deque
from io import StringIO
__all__ = ["shlex", "split"]
__all__ = ["shlex", "split", "quote"]
class shlex:
"A lexical analyzer class for simple shell-like syntaxes."
@ -274,6 +275,21 @@ def split(s, comments=False, posix=True):
lex.commenters = ''
return list(lex)
_find_unsafe = re.compile(r'[^\w\d@%_\-\+=:,\./]').search
def quote(s):
"""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 __name__ == '__main__':
if len(sys.argv) == 1:
lexer = shlex()