簡體   English   中英

如何轉義Python字符串中的任何特殊shell字符?

[英]How can I escape any of the special shell characters in a Python string?

如何轉義Python字符串中的任何特殊shell字符?

需要轉義以下字符:

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

比如說我有這個字符串:

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

TIA

在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`\;'

不確定為什么要逃避一切而不是盡可能多地引用,但是,這應該這樣做(如果需要,將'@'替換為字符串中不存在的另一個字符):

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

這可能是一點點逃避詭計,但不幸的是,字符串, re和shell,都使用\\ (反斜杠)進行轉義和其他特殊目的,確實使事情變得復雜:-)。

re.sub將完成這項工作:

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

產量

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM