首页 文章

Python,子进程,管道和选择

提问于
浏览
1

我有一个python程序,我不断读取通过subprocess.Popen启动的其他程序的输出,并通过subprocess.PIPE连接

我面临的问题是它有时会丢失已启动程序的大部分输出 .

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

这是相关的功能:

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行文件 . 另一方面,使用我的 ./pscript.py > /tmp/log2 给出一个大约5000行的文件 .

1 回答

  • 0

    在你的例子中,你完全忽略了stderr . 尝试创建这样的过程:

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

    此外,我将使用inotify直接使用其中一个Python bindings,而不是使用inotifywait生成进程 .

相关问题