首页 > 解决方案 > 在 subprocess.run 中遇到反斜杠

问题描述

我正在尝试处理 subprocess.run 的 Windows 路径中的反斜杠。我读过输出转义了反斜杠,这没什么好担心的。但是,看起来反斜杠实际上正在传递给 subprocess.run。我已经尝试了单 v 转义反斜杠的所有 8 种排列,使用 rv no r 和单 v 双引号,但似乎都没有。

我正在使用 shell=True 因为文档说我应该在使用 shell 内置的命令时使用。

请问有谁知道正确的咒语是什么?提前致谢。

这是我的尝试:


1.
subprocess.run(['dir C:\'], shell=True)

doesn't allow this

2.
subprocess.run(['dir C:\\'], shell=True)
'"dir C:\\"' is not recognized as an internal or external command,
operable program or batch file.
CompletedProcess(args=['dir C:\\'], returncode=1)

3. 
subprocess.run([r'dir C:\'], shell=True)

doesn't allow this

4.
subprocess.run([r'dir C:\\'], shell=True)
'"dir C:\\\\"' is not recognized as an internal or external command,
operable program or batch file.
CompletedProcess(args=['dir C:\\\\'], returncode=1)

5. 
subprocess.run(["dir C:\"], shell=True)

doesn't allow this

6.
subprocess.run(["dir C:\\"], shell=True)
'"dir C:\\"' is not recognized as an internal or external command,
operable program or batch file.
CompletedProcess(args=['dir C:\\'], returncode=1)

7.
subprocess.run([r"dir C:\"], shell=True)

doesn't allow this

8.
subprocess.run([r"dir C:\\"], shell=True)
'"dir C:\\\\"' is not recognized as an internal or external command,
operable program or batch file.
CompletedProcess(args=['dir C:\\\\'], returncode=1)



标签: python-3.x

解决方案


这有效:

import subprocess

subprocess.run('dir "C:/"', shell=True)

当您用单引号包围路径时,Windows 似乎不喜欢它(即使在 CMD 中)。当你给它双引号时它确实喜欢它。所以使用单引号来表示字符串和双引号来包围实际路径。此外,python(和 Windows)不介意在路径中使用正斜杠而不是反斜杠。是的,在这种情况下,您确实需要 shell=True。尽量远离它!


推荐阅读