在 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)



alex_bits

这有效:

import subprocess

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 subprocess.run python 中傳遞變量值

subprocess.run()中的CompletedProcess不返回字符串

如何使用超时从python的subprocess.run中捕获错误

mailutils无法通过subprocess.run在python中运行

subprocess.run 在参数中嵌入空字节

函数 subprocess.run 中的 env 参数有什么作用?

如何在 pytest 中模拟 subprocess.run?

循环内的Subprocess.run()

在Python中,如何在正在运行的子流程中引用从“ subprocess.run”传递的参数?

如何在python中的subprocess.run中运行复杂的查询

使用subprocess.run如何将每个循环的数据保存在不同的文件中?

如何使用subprocess.run回声(bash)的另一个文件中

使用 subprocess.run 中的“./”运行二进制文件

在基准测试时将 subprocess.run(....) 的输出写入 python3.5 中的文件

subprocess.run在Windows中不起作用-系统找不到指定的文件

TypeError:预期的str,字节或os.PathLike对象,而不是int;在subprocess.run()中

Beeline无法与python中的subprocess.run一起使用,永远卡住

为什么subprocess.run返回退出代码2,但日志中没有错误?

如何在 subprocess.run 中為參數 cwd 創建路徑

如何抑制或捕获subprocess.run()的输出?

终止使用“ subprocess.run”创建的进程

捕获 subprocess.run() 的输出并实时打印?

使用subprocess.run从终端读取输出

subprocess.run() 不返回任何输出

运行 subprocess.run 时捕获颜色

Subprocess.run()找不到路径

subprocess.run() 問題與 mkdir

subprocess.run简单方案失败

Python:脚本挂在 subprocess.run()