gpt4 book ai didi

python - 如何将 subprocess.run 的输出保存到字符串中?

转载 作者:行者123 更新时间:2023-12-01 07:37:48 26 4
gpt4 key购买 nike

我正在使用一个git命令

git log --format=%H 3c2232a5583711aa5f37d0f21014934f67913202

这里末尾的长字符串是提交 ID。此命令给出分支先前提交 ID 的列表。输出类似于,

3c2232a5583711aa5f37d0f21014934f67913202
9i45e2a5583711aa5f37d0f21014934f679132de

我试图在 python 中发出相同的命令,并尝试将输出存储在字符串中,如下所示,

import subprocess

result = subprocess.run(
[
"cd",
"/Users/XYZ/Desktop/gitrepo",
"git",
"log",
"3c2232a5583711aa5f37d0f21014934f67913202",
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
print(result.stdout.decode("utf-8"), type(result.stdout.decode("utf-8")))

但是打印的输出是空的!我尝试了 subprocess.run["-ls", "-l"] ,效果很好。 git 命令在命令行上工作,但我无法在字符串中捕获它。当我单独打印结果时,

CompletedProcess(args=['cd', '/Users/XYZ/Desktop/gitrepo', 'git', 'log', '3c2232a5583711aa5f37d0f21014934f67913202'], returncode=0, stdout=b'')

如何将 git 命令的输出保存在字符串中?我在一行中发出两个命令。我应该单独发出命令吗?如果我应该,我怎样才能(a)导航到 git 文件夹并(b)在那里发出 git 命令?

最佳答案

您的代码运行 cd "/Users/XYZ/Desktop/gitrepo""git""log""3c2232a5583711aa5f37d0f21014934f67913202" 这可能不是您想要的。

最好的方法不是将更改工作目录解释为单独的命令,而是将其作为运行 git 命令的环境设置的一部分。 The subprocess module has the keyword argument cwd for that.

If cwd is not None, the function changes the working directory to cwd before executing the child. In particular, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path.

这仅记录了 Popen 构造函数,但 subprocess.run documentation有这一段:

The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the Popen constructor - apart from timeout, input and check, all the arguments to this function are passed through to that interface.

所以你可以像这样重写你的代码:

import subprocess

result = subprocess.run(
[
"git",
"log",
"3c2232a5583711aa5f37d0f21014934f67913202",
],
cwd="/Users/XYZ/Desktop/gitrepo"
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
print(result.stdout.decode("utf-8"), type(result.stdout.decode("utf-8")))

关于python - 如何将 subprocess.run 的输出保存到字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56893355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com