Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- backslash_shell_quote_re = re.compile(r'([^A-Za-z0-9_.,:/])')
- def shell_escape(s, flavor='sh'):
- """
- Escape a random string (s) so that it reads as a single word when
- undergoing shell command-line parsing.
- The default flavor should be safe for all mainstream shells I know
- about, but there are some other escaping modes which may result in
- more compact or more readable output.
- Available flavors:
- bash, zsh: use dollar-quoting ($'foo')
- sh, csh: use standard single-quotes except when quoting single-
- quote characters
- backslash: use no quotes; escape all unsafe characters with a
- backslash
- """
- if flavor in ('bash', 'zsh'):
- return "$'%s'" % s.replace('\\', '\\\\').replace("'", "\\'")
- elif flavor in ('sh', 'csh'):
- return "'%s'" % s.replace("'", "'\"'\"'")
- elif flavor == 'backslash':
- return backslash_shell_quote_re.sub(r'\\\1', s)
- else:
- raise ValueError("Unknown shell quoting flavor %s" % flavor)
Add Comment
Please, Sign In to add comment