python-3.x - 在 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)
解决方案
这有效:
import subprocess
subprocess.run('dir "C:/"', shell=True)
当您用单引号包围路径时,Windows 似乎不喜欢它(即使在 CMD 中)。当你给它双引号时它确实喜欢它。所以使用单引号来表示字符串和双引号来包围实际路径。此外,python(和 Windows)不介意在路径中使用正斜杠而不是反斜杠。是的,在这种情况下,您确实需要 shell=True。尽量远离它!
推荐阅读
- python-3.x - 部分响应(API)
- c# - Unity 2D 格斗游戏相机
- java - java.lang.StackOverflowError - Kickstart 问题(2019 Round C Wiggle Walk)
- ember.js - WatcherAdapter 的第一个参数必须是 SourceNodeWrapper 节点的数组
- oracle - Birt 报告在 LONGDESCRIPTION CLOB 字段中存储 4000 个字符后跳过字母/行
- python - 从 Json 返回特定路径 python 的值
- firefox - Mozilla Firefox 原生消息传递错误:没有这样的原生应用程序
- r - 将 2dim 数组从 C 返回到 R
- javascript - 如何从画布中选择或复制文本?
- python - 准确率高,预测差 - CNN 和 TensorFlow Python