Python,子进程,管道和选择

我有一个Python程序,我不断读取通过subprocess.Popen启动的其他程序的输出,并通过子进程连接.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行的文件。


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

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

此外,我会直接使用它的一个Python绑定进行inotify,而不是用inotifywait产生一个进程。

链接地址: http://www.djcxy.com/p/77115.html

上一篇: Python, subprocess, pipe and select

下一篇: Python windows script subprocess continues to output after script ends