From b2135cdea36caccb04acee7d78cd370fd5a3a678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89ric=20Araujo?= Date: Wed, 27 Jul 2011 18:29:31 +0200 Subject: Add shlex.quote function, to escape filenames and command lines (#9723). MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- Lib/shlex.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'Lib/shlex.py') diff --git a/Lib/shlex.py b/Lib/shlex.py index 3edd3db1ed..279ab48405 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -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() -- cgit v1.2.1 From 7f215a8d023e6e561f3d4991ce119f25c35a7c95 Mon Sep 17 00:00:00 2001 From: Ezio Melotti Date: Tue, 16 Aug 2011 19:03:41 +0300 Subject: #9723: refactor regex. --- Lib/shlex.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'Lib/shlex.py') diff --git a/Lib/shlex.py b/Lib/shlex.py index 92c49c3608..69f3b456af 100644 --- a/Lib/shlex.py +++ b/Lib/shlex.py @@ -276,7 +276,7 @@ def split(s, comments=False, posix=True): return list(lex) -_find_unsafe = re.compile(r'[^\w@%\-\+=:,\./]', re.ASCII).search +_find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search def quote(s): """Return a shell-escaped version of the string *s*.""" -- cgit v1.2.1