使用 Python 子进程处理带括号的文件路径
Processing file paths with parentheses with Python subprocess
我要处理的文件的路径中包含括号。
path = "/dir/file (with parentheses).txt"
我正尝试在 Python 中按如下方式处理它们:
subprocess.call("./process %s" % path, shell=True)
但是,我得到以下错误
/bin/sh: 1: Syntax error: "(" unexpected
如何传递正确的字符串来处理正确的路径?
试试这个
subprocess.call('./process "%s"' % path, shell=True)
我想问题更多的是文件名中的 space。带有 spaces 的文件名应该用这样的引号引起来 ./process "foo bar.txt"
或像这样转义 ./process foo\ bar.txt
.
不要使用 shell=True
。它很容易出问题(如 OP 中所示)并启用 shell injection attacks.
这样做:
subprocess.call(["./process", path])
如果您坚持使用 shell=True
,请阅读 python 文档中的 Security Considerations,并确保您使用 shlex.quote
正确转义所有元字符。
我要处理的文件的路径中包含括号。
path = "/dir/file (with parentheses).txt"
我正尝试在 Python 中按如下方式处理它们:
subprocess.call("./process %s" % path, shell=True)
但是,我得到以下错误
/bin/sh: 1: Syntax error: "(" unexpected
如何传递正确的字符串来处理正确的路径?
试试这个
subprocess.call('./process "%s"' % path, shell=True)
我想问题更多的是文件名中的 space。带有 spaces 的文件名应该用这样的引号引起来 ./process "foo bar.txt"
或像这样转义 ./process foo\ bar.txt
.
不要使用 shell=True
。它很容易出问题(如 OP 中所示)并启用 shell injection attacks.
这样做:
subprocess.call(["./process", path])
如果您坚持使用 shell=True
,请阅读 python 文档中的 Security Considerations,并确保您使用 shlex.quote
正确转义所有元字符。