python popen sqlplus_Python基于Select模型实现Popen输出
参考了pssh的代码,实现了下面一个小的框架,用于实现并发处理涉及到的IO返回的标准输出和错误输出。IOMap里面保存了所有可读句柄对应的call函数。一旦select返回就read返回然后相应的处理,直接看代码吧。
#!/usr/bin/env python
#coding=utf-8
import os
import signal
import select, sys, subprocess
BUFFER_SIZE = 1024
class IOMap(object):
"""A manager for file descriptors and their associated handlers.
The poll method dispatches events to the appropriate handlers.
"""
def __init__(self):
self.readmap = {}
self.writemap = {}
wakeup_readfd, wakeup_writefd = os.pipe()
self.register_read(wakeup_readfd, self.wakeup_handler)
# TODO: remove test when we stop supporting Python <2.5
if hasattr(signal, 'set_wakeup_fd'):
signal.set_wakeup_fd(wakeup_writefd)
self.wakeup_writefd = None
else:
self.wakeup_writefd = wakeup_writefd
def register_read(self, fd, handler):
"""Registers an IO handler for a file descriptor for reading."""
self.readmap[fd] = handler
def register_write(self, fd, handler):
"""Registers an IO handler for a file descriptor for writing."""
self.writemap[fd] = handler
def unregister(self, fd):
"""Unregisters the given file descriptor."""
if fd in self.readmap:
del self.readmap[fd]
if fd in self.writemap:
del self.writemap[fd]
def poll(self, timeout=None):
"""Performs a poll and dispatches the resulting events."""
if not self.readmap and not self.writemap:
return
rlist = list(self.readmap)
wlist = list(self.writemap)
try:
rlist, wlist, _ = select.select(rlist, wlist, [], timeout)
except select.error:
_, e, _ = sys.exc_info()
errno = e.args[0]
if errno == EINTR:
return
else:
raise
for fd in rlist:
handler = self.readmap[fd]
handler(fd, self)
for fd in wlist:
handler = self.writemap[fd]
handler(fd, self)
def wakeup_handler(self, fd, iomap):
"""Handles read events on the signal wakeup pipe.
This ensures that SIGCHLD signals aren't lost.
"""
try:
os.read(fd, READ_SIZE)
except (OSError, IOError):
_, e, _ = sys.exc_info()
errno, message = e.args
if errno != EINTR:
sys.stderr.write('Fatal error reading from wakeup pipe: %s\n'% message)
raise FatalError
class Task(object):
"""docstring for Task"""
def __init__(self,):
self.stdout = ""
self.stderr = ""
def run(self, io_map):
"""run command in Popen
print stdout and stderr
"""
test_pipe = subprocess.Popen('i=0;while [ $i -lt 1000 ];do echo "hello world $i";abcd;let i++;done', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.stdout = test_pipe.stdout
self.stderr = test_pipe.stderr
io_map.register_read(self.stdout.fileno(), self.handle_stdout)
io_map.register_read(self.stderr.fileno(), self.handle_stderr)
while True:
try:
io_map.poll()
except KeyboardInterrupt:
# This exception handler doesn't print out any fancy status
# information--it just stops.
self.interrupted()
def handle_stdout(self, fd, iomap):
""" handle Popen return stdout
"""
try:
buf = os.read(fd, BUFFER_SIZE)
if buf:
print "stdout : " + buf,
else:
self.close_stdout(iomap)
except (OSError, IOError):
_, e, _ = sys.exc_info()
if e.errno != EINTR:
self.close_stdout(iomap)
pass
def handle_stderr(self, fd, iomap):
""" handle Popen return stderr
"""
try:
buf = os.read(fd, BUFFER_SIZE)
if buf:
print "stderr : " + buf,
else:
self.close_stderr(iomap)
except (OSError, IOError):
_, e, _ = sys.exc_info()
if e.errno != EINTR:
self.close_stderr(iomap)
pass
def close_stderr(self, iomap):
if self.stderr:
iomap.unregister(self.stderr.fileno())
def close_stdout(self, iomap):
if self.stdout:
iomap.unregister(self.stdout.fileno())
def interrupted(self):
"""Cleans up after a keyboard interrupt."""
sys.exit(255)
if __name__ == '__main__':
iomap = IOMap()
task = Task()
task.run(iomap)
python popen sqlplus_Python基于Select模型实现Popen输出相关推荐
- 基于select模型的TCP服务器
之前的一篇博文是基于TCP的服务器和客户机程序,今天在这我要实现一个基于select模型的TCP服务器(仅实现了服务器). socket套接字编程提供了很多模型来使服务器高效的接受客户端的请求,sel ...
- 使用socket实现基于select模型的网络聊天室
假期闲来无事,便写了个小小的网络聊天室程序.以前一直都是写MFC的有界面的程序,时间长了,便失去了兴趣,感觉有些东西经过MFC的封装,反而失去了意义,让人学不到东西,所以,丢开MFC那层的东西,直接使 ...
- MFC基于select模型的套接字类之服务器(1)
C/S(Client/Server)结构的网络软件分为客户端和服务端.客户端和服务端担任不同的任务.一般来说,客户端将用户的需求提交给服务端,再将服务端返回的结果以一定形式提供给用户.服务端的任务是接 ...
- python subprocess popen 多次重定向_python subprocess.Popen系列问题
最近在项目中遇到一个需求,前端发来一个命令,这个命令是去执行传递过来的一个脚本(shell 或者python),并返回脚本的标准输出和标准出错,如果执行超过设定时间还没结束就超时,然后终止脚本的执行. ...
- python基于tpot训练模型并抑制输出stackingestimator、而是输出单模型例如xgboost设置
python基于tpot训练模型并抑制输出stackingestimator.而是输出单模型例如xgboost设置 目录 python基于tpot训练模型并抑制输出stackingestimat
- 基于Python的信用评分卡模型分析
目录 一.项目流程 二.数据获取 三.数据预处理 3.1 缺失值处理 3.2 异常值处理 3.3 数据切分 信用风险计量体系包括主体评级模型和债项评级两部分.主体评级和债项评级均有一系列评级模型组成, ...
- 基于共享内存、信号、命名管道和Select模型实现聊天窗口
基于共享内存.信号.命名管道和Select模型实现聊天窗口 问题模型 A.B两个进程通过管道通信,A 进程每次接收到的数据通过共享内存传递给A1进程显示,同理,B进程每次接收到的数据通过共享内存传递给 ...
- python信用评分卡_基于Python的信用评分卡模型分析(二)
上一篇文章基于Python的信用评分卡模型分析(一)已经介绍了信用评分卡模型的数据预处理.探索性数据分析.变量分箱和变量选择等.接下来我们将继续讨论信用评分卡的模型实现和分析,信用评分的方法和自动评分 ...
- 基于ArcGIS Pro、Python、USLE、INVEST模型等多技术融合的生态系统服务构建生态安全格局
近年来,由于社会经济的快速发展和人口增长,社会活动对环境的压力不断增大,人地矛盾加剧.虽然全球各国在生态环境的建设和保护上已取得不少成果,但还是未从根本上转变生态环境的恶化趋势:生态破坏.环境退化.生 ...
最新文章
- linux环境中,查询网卡的速度(带宽)
- windows 搭建python 虚拟环境 写程序_Windows下搭建Python虚拟环境
- python123电脑登录不了_Python-用户登陆,密码失败3次,账户将被锁住(login)
- python链表_使用python实现链表操作
- NeHe OpenGL教程 第三十七课:卡通映射
- git push ! [remote rejected] master -> master (pre-receive hook declined)
- 【转】处理百万级以上的数据提高查询速度的方法
- 【BZOJ3942】Censoring [KMP]
- 【渝粤教育】电大中专药物分析技术基础 (2)_1作业 题库
- linux定时器时间来源,linux 时间定时器 介绍
- itunes安装后不能用,双击后等很长时间,提示:ITUNES 驱动程序缺少用于导入和刻录的CD与DVD注册的设置...
- 创建企业级地理数据库
- 用photoshop将图片不失真的放大
- 5000头奶牛的数字化之旅
- 发射功率 接收灵敏度 RF射频传输 原理 介绍 三分钟看懂 详解!
- uva10099+uvauva10048
- 双拼输入法的原理及上手方法
- 户外大覆盖无线访问接入AP?
- linux win10启动不了怎么办,win10不能启动怎么办?win10无法正常启动的解决方法
- 变身成为互联网设计师
热门文章
- Cookie对象知识总结
- 【JUC并发编程01】JUC概述
- 带你学python基础:条件控制if与循环语句while、for 以及range函数
- 【KVM系列02】KVM的CPU 和内存虚拟化
- 【KVM系列01】KVM简介及安装
- 数据库隔离级别---MySQL的默认隔离级别就是Repeatable,Oracle默认Read committed,最高级别Serializable
- SpringMVC的表单标签库
- [转]在Fedora上安装Oracle 11g XE
- Mq安装服务器文件传输,RabbitMQ学习:安装RabbitMQ及RabbitMQ的初步配置(一)
- php header x-auth-token,使用Angular 2正确设置Header X-Auth-Token