gpt4 book ai didi

Python 解析子进程输出

转载 作者:太空宇宙 更新时间:2023-11-03 18:06:43 25 4
gpt4 key购买 nike

我正在尝试保存

的输出
git remote show origin 

  tempf = open('.tmp', 'w+')
tempf2 = open('.tmp2', 'w+')
subprocess.Popen(["git", "remote", "show", "origin"], stdout=tempf, stderr=tempf2)
tempf.close()
tempf2.close()
output = open('.tmp', 'r')
gitoutput = output.read()

然后使用正则表达式解析输出。

但是,上面的代码始终为 gitoutput 返回 None

我有什么遗漏的吗?我很困惑,因为应用 .seek(0) 不会更改输出,而运行 cat .tmp 显示正确的内容。

编辑:stderr 也会被捕获 (stderr=tempf2) 并被丢弃,因为 git 服务器在运行脚本时会向命令行产生不需要的输出。

最佳答案

.wait()与Popen结合使用

import subprocess
with open('.tmp', 'w+') as tempf, open('.tmp2', 'w+') as tempf2:
proc = subprocess.Popen(["git", "remote", "show", "origin"], stdout=tempf, stderr=tempf2)
proc.wait()
tempf.seek(0)
gitoutput = tempf.read()
print(gitoutput)

或者只使用check_call:

with open('.tmp', 'w+') as tempf,  open('.tmp2', 'w+') as tempf2:
proc = subprocess.check_call(["git", "remote", "show", "origin"], stdout=tempf, stderr=tempf2)
tempf.seek(0)
gitoutput = tempf.read()
print(gitoutput)

关于Python 解析子进程输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26747349/

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