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

Sam*_*rts 4 python bash shell

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

需要转义以下字符:

$,!,#,&,",',(,),|,<,>,`,\,;
Run Code Online (Sandbox Code Playgroud)

比如说我有这个字符串:

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

TIA

5go*_*der 7

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

shlex.quote(s)
Run Code Online (Sandbox Code Playgroud)

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

在你的例子中:

import shlex

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

输出:

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