最近开始学习python,今天工作需要获取shell 命令的输出,之前都是使用os.system 、commands实现的,想起subprocess应该也可以,查了下资料,实现了一个简单的实时读取日志脚本:
-
#!/usr/bin/python
-
#--*-- coding:utf-8 --*--
-
import subprocess
-
-
sp = subprocess.Popen('tail -f /var/log/web/server.log',shell=True,stdout=subprocess.PIPE)
-
while sp.poll() == None :
-
print sp.stdout.readline()
-
print sp.returncode
Popen.poll() 检查子进程是否结束,设置并返回returncode
Popen.wait() 等待子进程结束,设置并返回returncode,会等待子进程结束一起返回输出结果
Warning
This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough
output to a pipe such that it blocks waiting for the OS pipe buffer to accept
more data. Use to avoid that.
阅读(2381) | 评论(0) | 转发(0) |