gpt4 book ai didi

python - 将 stdout 从 subprocess.check_call 重定向到函数?

转载 作者:行者123 更新时间:2023-11-28 18:54:32 31 4
gpt4 key购买 nike

调用 subprocess.check_call() 允许为 stdout 指定文件对象,但在将数据写入文件之前,我想逐行修改它们。

我目前将输出重定向到一个临时文件(由 tempfile.TemporaryFile() 创建)。check_call 完成后,我逐行读取该临时文件,进行修改并编写最终输出文件。

由于输出很大,纯内存解决方案不可行,我想即时修改数据并直接写入最终输出文件。

有人知道如何实现吗?

最佳答案

def check_call_modify(command, modifier_function, output_file)
p = subprocess.Popen(command, stdout=subprocess.PIPE)
for line in p.stdout:
line = modifier_function(line)
output_file.write(line)
p.wait()
if p.returncode:
raise subprocess.CalledProcessError(p.returncode, command)
return p.returncode

使用它传递一个函数来修改每一行和文件。下面的愚蠢示例将以大写形式将 ls -l 的结果保存到 listupper.txt:

with open('listupper.txt', 'w') as f:
check_call_modify(['ls', '-l'], operator.methodcaller('upper'), f)

关于python - 将 stdout 从 subprocess.check_call 重定向到函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5487898/

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