Chinaunix首页 | 论坛 | 博客
  • 博客访问: 277464
  • 博文数量: 73
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 452
  • 用 户 组: 普通用户
  • 注册时间: 2014-09-22 17:07
个人简介

心态决定命运

文章分类

全部博文(73)

文章存档

2017年(21)

2016年(27)

2015年(21)

2014年(4)

我的朋友

分类: Python/Ruby

2016-04-28 10:07:08

   最近开始学习python,今天工作需要获取shell 命令的输出,之前都是使用os.system 、commands实现的,想起subprocess应该也可以,查了下资料,实现了一个简单的实时读取日志脚本:

点击(此处)折叠或打开

  1. #!/usr/bin/python
  2. #--*-- coding:utf-8 --*--
  3. import subprocess

  4. sp = subprocess.Popen('tail -f /var/log/web/server.log',shell=True,stdout=subprocess.PIPE)
  5. while sp.poll() == None :
  6.     print sp.stdout.readline()
  7. 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.



阅读(2315) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~