python 执行linux 命令得到输出

python 执行linux 命令得到输出
1, subprocess.Popen() 用法
import subprocess
subprocess.Popen(["ls","-l"]) # 列表第一个参数是指的是命令 其余的指的是命令参数
child = subprocess.Popen('ping www.baidu.com',shell=True)  # 字符串
child.poll()           # 检查子进程状态
child.kill()           # 终止子进程
child.send_signal()    # 向子进程发送信号
child.terminate()      # 终止子进程
2 tempfile.mkstemp() 新建临时文件
# 使用实例!
import shlex
import logging
logger = logging.getLogger(__name__)


class OSUtil(object):
    @staticmethod
    def safe_popen(cmd, timeout=None, interval=10, **params):
        import os, subprocess, tempfile, time
        logger.debug(cmd)
        interval = interval
        # to get a temp file Name from system 
        fd1, fn1 = tempfile.mkstemp(suffix='.log', prefix='openhpc_stdout_')
        fd2, fn2 = tempfile.mkstemp(suffix='.log', prefix='openhpc_stderr_')
        os.close(fd1)
        os.close(fd2)

        f1 = None
        f2 = None
        try:
            rc = None
            pobj = subprocess.Popen(cmd, stdout=open(fn1, 'w'), stderr=open(fn2, 'w'))
            
            if timeout > 0:
                start = time.time()
                # Check if the child process is finished and return the status!
                # it return None when it down
                rc = pobj.poll()
                while rc is None:  # loop if process is still running
                    if timeout < time.time() - start:
                        pobj.kill()
                        break
                    # Check every 10 seconds when job long ago
                    time.sleep(interval)
                    rc = pobj.poll()
            else:
                rc = pobj.wait()
            
            outstr, errstr = '', ''
            try:
                f1 = open(fn1)          
                line = f1.readline()
                while line:    
                    outstr += line
                    line = f1.readline()
                f1.close()
                f1 = None
                os.remove(fn1)
                
                f2 = open(fn2)          
                line = f2.readline()
                while line:    
                    errstr += line
                    line = f2.readline()
                f2.close()
                f2 = None
                os.remove(fn2)
            except Exception:
                logger.error("exception")
            logger.debug(outstr)
            logger.debug(errstr)
            return rc, outstr, errstr
        finally:
            if f1 is not None:
                f1.close()
            if f2 is not None:
                f2.close()
View Code
调用实例
import threading
g_jobop_lock = threading.RLock()
g_jobop_lock.acquire()
execmd = ['ls','-a']
OSUtil.safe_popen(execmd)
g_jobop_lock.release()
View Code

 

posted @ 2018-12-17 21:06  十七楼的羊  阅读(3547)  评论(0编辑  收藏  举报