ide*_*n42 4 python shell escaping
我有兴趣在Python3.x中转义字符串,例如:
SOME_MACRO(a, b)
Run Code Online (Sandbox Code Playgroud)
成...
SOME_MACRO\(a,\ b\)
Run Code Online (Sandbox Code Playgroud)
...这样它就可以作为定义传递给程序(在本例中不是gcc),
例如,
some_program -DSOME_MACRO\(a,\ b\)="some expression"
Run Code Online (Sandbox Code Playgroud)
我希望shlex有这个功能,但我没有找到如何做到这一点并检查了许多类似的问题.
我不介意写一些简单的函数来做到这一点,但这似乎是Python所包含的东西.
注意: 程序我传递的参数不会接受:
-D"SOME_MACRO(a, b)"="some expression"
Run Code Online (Sandbox Code Playgroud)
...它希望第一个字符是标识符.
在Python 3.3中,您可以使用shlex.quote返回字符串的shell转义版本.它是pipes.quote的继承者,自Python 1.6以来已被弃用.请注意,文档建议在不能使用列表的情况下,如另一个答案中所建议的那样.另外根据文档,引用与UNIX shell兼容.我不能保证它会适用于你的情况,但是快速测试rm,使用pipes因为我没有Python 3.3:
$ touch \(a\ b\)
$ ls
(a b)
>>> import subprocess, pipes
>>> filename = pipes.quote("(a b)")
>>> command = 'rm {}'.format(filename)
>>> subprocess.Popen(command, shell=True)
$ ls
$
Run Code Online (Sandbox Code Playgroud)
正确地做到这一点意味着不必担心这一点。shell 必须担心空格、引号和括号;Python 没有。
proc = subprocess.Popen([..., "-DSOME_MACRO(a, b)=some expression", ...], ...)
Run Code Online (Sandbox Code Playgroud)