使用Python子进程处理带括号的文件路径

Oli*_*ier 2 python linux bash subprocess

我要处理的文件的路径中包含括号。

path = "/dir/file (with parentheses).txt"
Run Code Online (Sandbox Code Playgroud)

我正在尝试用 Python 处理它们,如下所示:

subprocess.call("./process %s" % path, shell=True)
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误

/bin/sh: 1: Syntax error: "(" unexpected
Run Code Online (Sandbox Code Playgroud)

如何传递正确的字符串来处理正确的路径?

ric*_*ici 5

不要使用shell=True. 它很容易出现问题(如OP中所示)并且可以进行shell注入攻击

像这样做:

subprocess.call(["./process", path])
Run Code Online (Sandbox Code Playgroud)

如果您坚持使用shell=True,请阅读python 文档中的安全注意事项,并确保您使用shlex.quote正确转义所有元字符。