天天看点

python的subprocess模块实战 与 Linux 输出流重定向

在Liunx上面,会进行一些部署和监控的操作。

有时候使用crontab直接调用shell可以满足一定需求,但是最近在接受一部分运维项目的时候会发现。

部分脚本运行的过程中,stdout和stderr的输出流会无故丢失。

目前本人可以想到的方法,是利用python的subprocess模块进行调用,并记录下对应的stdout和stderr日志。

这里是一个实验,首先是一个python脚本。

模拟调用过程中会产生stdout日志和stderr信息。

#!/usr/bin/env python
'''output test data to sys.stdout , sys.stderr'''
import sys

sys.stdout.write('hello in \n')
sys.stderr.write('wolrd in \n')
           

在Linux上面通过subprocess模块进行调用shell。并收集其对应输出的信息。

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

import shlex, subprocess
p = subprocess.Popen("python stdTest.py",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
sout = p.stdout.readlines()
serr = p.stderr.readlines()
print sout
print serr
           

上面的代码中,主要使用了subprocess中的Popen对象。

shell=True  表示调用本地的shell,必选。

stdout=subprocess.PIPE

stderr=subprocess.PIPE

分表把stdout和stderr重定向到PIPE这个对象里面。进行缓存。

也可以在调用多个subprocess的时候,进行通信。

python stdTest.py 2> tmp.log

显示stdout的内容
hello in

cat tmp.log
显示内容
wolrd in      

默认情况下,stdout和stderr都会输出到console上面。

但是很多程序会通过配置文件,把stdout,stderr分别写入对应的文件中。  

可以通过这个方式,进行stderr,stdout重定向:

command 2>&1 > tmp.log
表示把stderr输出流,重定向到stdout输出流。
再一同输出到tmp.log中      

其中标准的输入,输出和错误输出分别表示为STDIN,STDOUT,STDERR,也可以用0,1,2来表示。

command 3>&2 2>&1 1>&3 实现标准输出和错误输出的交换

command > filename 2>&1 把标准输出和标准错误一起重定向到一个文件中

 refer to: http://www.cnblogs.com/yangyongzhi/p/3364939.html