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

标签 python redirect callback stdout

调用 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/

相关文章:

redirect - SSL 证书和重定向

JAVASCRIPT:在本地主机上成功 Ajax 响应后重定向到主页

c - 了解 C 中回调的情况

javascript - 如何从被调用函数获得响应?

python - 如果通过并且如果在 python 中继续

python - 用户无权查询 bigquery 表

python - Scrapy 和 XPath 通用选择

python - wtforms 表单类子类化和字段排序

exception-handling - 异常 : redirect or render?

ruby-on-rails - Rails ActiveRecord::RecordInvalid 异常未在关联的 after_create 中引发