subprocess.run() 与 capture_output=True

问题描述 投票:0回答:1

我对 Python 很陌生。 我正在尝试通过 Python 的

subprocess.run()
运行一些 shell 命令。 我还想捕获 shell 命令的输出。 当我使用
capture_output=False
运行命令时,它似乎运行良好。 但是当我将其切换到
True
时,我收到错误。

import subprocess

# runs just fine
subprocess.run("git --version", capture_output=False)

# throws error
subprocess.run("git --version", capture_output=True)
## OSError: [WinError 6] The handle is invalid

经过进一步调查,我认为发生这种情况是因为我使用 Rstudio 作为我的 IDE。 当我尝试在 Python shell 中运行它时,它工作得很好。

python subprocess
1个回答
0
投票

发生错误的原因是

subprocess.run()
capture_output=True
无法与作为字符串传递的 shell 命令正常工作。相反,将命令作为列表传递:

import subprocess

# Correct way to capture output
result = subprocess.run(["git", "--version"], capture_output=True, text=True)

# Output
print(result.stdout)
#capture_output=True captures both stdout and stderr.
#text=True returns the output as a string instead of bytes.
© www.soinside.com 2019 - 2024. All rights reserved.