如何转义Python字符串中的任何特殊shell字符?

时间:2015-01-24 00:23:50

标签: python bash shell

如何转义Python字符串中的任何特殊shell字符?

以下字符需要转义:

$,!,#,&,",',(,),|,<,>,`,\,;

例如说我有这个字符串:

str="The$!cat#&ran\"'up()a|<>tree`\;"

TIA

3 个答案:

答案 0 :(得分:6)

在Python3中,所需的电池包含在shlex.quote中。

shlex.quote(s)
     

返回字符串 s 的shell转义版本。返回的值是一个字符串,可以安全地用作shell命令行中的一个标记。

在你的例子中:

import shlex

s = "The$!cat#&ran\"'up()a|<>tree`\;"
print(shlex.quote(s))

输出:

'The$!cat#&ran"'"'"'up()a|<>tree`\;'

答案 1 :(得分:1)

不确定为什么要逃避一切而不是尽可能多地引用,但是,这应该这样做(如果需要,将'@'替换为字符串中不存在的另一个字符):

>>> escape_these = r'([$!#&"()|<>`\;' + "'])"
>>> print(re.sub(escape_these, r'@\1', s).replace('@','\\'))
The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\;

这可能是一点点逃避诡计,但不幸的是,字符串re和shell都使用\(反斜杠)进行转义和其他特殊目的,确实让事情变得复杂: - )。

答案 2 :(得分:0)

re.sub将完成这项工作:

re.sub("(!|\$|#|&|\"|\'|\(|\)|\||<|>|`|\\\|;)", r"\\\1", astr)

<强>输出

The\$\!cat\#\&ran\"\'up\(\)a\|\<\>tree\`\\\;
相关问题