我正在尝试处理 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)
这有效:
import subprocess
subprocess.run('dir "C:/"', shell=True)
当您用单引号将路径括起来时,Windows 似乎不喜欢它(即使在 CMD 中)。当你给它双引号时,它确实喜欢它。因此,使用单引号表示字符串并使用双引号将实际路径括起来。此外,python(和 Windows)不介意在路径中使用正斜杠而不是反斜杠。是的,在这种情况下,您确实需要 shell=True。尽量远离它吧!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句