375   Python

一,背景
1,subprocess.Popen 创建的子进程通过管道形式跟主进程进行数据交互
2,子进程输出内容是管道式的,当没有内容时会一直处于读阻塞
3,读取子进程输出时采取非阻塞,以便主进程执行循环计时,以及杀掉子进程

二,实例代码

#!/usr/bin/env python
# coding=utf-8

import subprocess
import threading
import logging
import signal
import os, sys, time, pwd
import fcntl


def nonBlockRead(output):
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        #return output.read()
        return output.readline()
    except:
        return ''

def main(SHELL,TIME_MAX):

    p = subprocess.Popen(SHELL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, close_fds=True, preexec_fn=os.setsid)

    time_count = TIME_MAX
    stoptime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() + time_count))

    while True:
        # timeout
        thistime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        print 'count time : ' + thistime 
        if thistime >= stoptime:
            os.killpg(os.getpgid(p.pid), signal.SIGTERM)
            break
        # line = p.stdout.readline()
        line = nonBlockRead(p.stdout)
        if line :
            print '>> ' +  line
            continue


if __name__ == '__main__':
    SHELL = 'top'
    TIME_MAX = 10
    main(SHELL,TIME_MAX)





Leave a Reply

Your email address will not be published. Required fields are marked *