Guest User

Untitled

a guest
Jul 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. import re
  2.  
  3. backslash_shell_quote_re = re.compile(r'([^A-Za-z0-9_.,:/])')
  4. def shell_escape(s, flavor='sh'):
  5. """
  6. Escape a random string (s) so that it reads as a single word when
  7. undergoing shell command-line parsing.
  8.  
  9. The default flavor should be safe for all mainstream shells I know
  10. about, but there are some other escaping modes which may result in
  11. more compact or more readable output.
  12.  
  13. Available flavors:
  14. bash, zsh: use dollar-quoting ($'foo')
  15. sh, csh: use standard single-quotes except when quoting single-
  16. quote characters
  17. backslash: use no quotes; escape all unsafe characters with a
  18. backslash
  19.  
  20. """
  21.  
  22. if flavor in ('bash', 'zsh'):
  23. return "$'%s'" % s.replace('\\', '\\\\').replace("'", "\\'")
  24. elif flavor in ('sh', 'csh'):
  25. return "'%s'" % s.replace("'", "'\"'\"'")
  26. elif flavor == 'backslash':
  27. return backslash_shell_quote_re.sub(r'\\\1', s)
  28. else:
  29. raise ValueError("Unknown shell quoting flavor %s" % flavor)
Add Comment
Please, Sign In to add comment