如果程序重新启动,如何将程序的管道输出保持为python脚本 [英] How to keep piping output of a program to a python script, if the program is restarted

查看:102
本文介绍了如果程序重新启动,如何将程序的管道输出保持为python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以通过例如Python读取另一个脚本的输出。调用 some_program | print_input.py 并在 print_input.py 中使用 sys.stdin ,如下所示:

I know i can read the output of another script in Python by e.g. calling some_program | print_input.py and using sys.stdin in print_input.py like this:

import sys
if __name__=='__main__':
    while True:
        print sys.stdin.read(1024)

但是也可以重启 some_program 仍然得到它的输出而不重新启动 print_input.py

But is it also possible to restart some_program and still get its output without restarting print_input.py?

这个想法是脚本 some_program 可能会崩溃,因此我必须重新启动它,而不会丢失当前状态 print_input.py

The idea is that the script some_program may crash, so that i will have to restart it, without loosing the current state of print_input.py.

可能需要的其他信息:


  1. 启动 some_program 来自 print_input.py 使用例如不幸的是,子流程不是一个选项。

  2. 低延迟要求,因此没有(长期)阻止呼叫。

  3. some_program 的输出很大。

  4. 我无法修改 some_program

  1. Launching some_program from within print_input.py using e.g. subprocess is not an option unfortunately.
  2. Low latency requirements, so no (long) blocking calls.
  3. The output of some_program is massive.
  4. I can't modify some_program.


推荐答案

优雅/通常的解决方案是使用命名管道。使用mkfifo创建一个管道,将 some_program 的输出传递给它,python脚本只能从管道中读取。这两个程序都可以重新启动而不会出现问题。

The elegant/usual solution would be to use named pipes. Create a pipe using mkfifo , pipe the output of some_program to it and the python script can just read from the pipe. Both program can be restarted without issues.

我不确定性能但不应该涉及IO(即使管道似乎是一个文件)。

Im not sure about performance but no IO should be involved (even thought the pipe seems to be a file).

另一种可能性是在tmpfs或ramfs文件系统中创建一个临时文件,有 some_program 写入它,以及python脚本可以反复尝试阅读。但IMO这比使用管道要严格得多..

Another possibility would be to create a temporary file in a tmpfs or ramfs filesystem, have some_program write to it, and the python script can just repeatedly try reading. But IMO this is strictly worse than using pipes..

这篇关于如果程序重新启动,如何将程序的管道输出保持为python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆