Python、子进程、管道和

2024-09-22 16:35:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序,在这个程序中我不断地读取通过子流程.Popen并通过子流程.管道在

我面临的问题是,它有时会失去启动程序的一部分输出。在

例如,通过到inotifywait的管道监视inotify事件会丢失许多事件。在

相关功能如下:


    process = subprocess.Popen(["inotifywait", "-q", "-r", "-m", 
      "--format", "%e:::::%w%f", srcroot], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    polling = select.poll()
    polling.register(process.stdout)
    process.stdout.flush()

    while True:
        process.stdout.flush()
        if polling.poll(max_seconds*1000):
            line = process.stdout.readline()
            if len(line) > 0:
                print line[:-1]

执行命令inotifywait -q -r -m --format %e:::::%w%f /opt/fileserver/ > /tmp/log1并移动一些文件(以生成inotify事件),得到一个大于8000行的文件。另一方面,使用my ./pscript.py > /tmp/log2给出一个包含大约5000行的文件。在


Tags: 文件程序format管道stdoutline事件流程
1条回答
网友
1楼 · 发布于 2024-09-22 16:35:04

在您的示例中,您完全忽略了stderr。尝试创建如下流程:

process = subprocess.Popen(["inotifywait", "-q", "-r", "-m", 
  " format", "%e:::::%w%f", srcroot], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

此外,我将直接将inotify与它的一个Python bindings一起使用,而不是用inotifywait生成一个进程。在

相关问题 更多 >