- 浏览: 1999384 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (651)
- ACE (35)
- BAT (9)
- C/C++ (116)
- fast-cgi (14)
- COM (27)
- python (59)
- CGI (4)
- C# (2)
- VC (84)
- DataBase (29)
- Linux (96)
- P2P (6)
- PHP (15)
- Web (6)
- Memcached (7)
- IME输入法 (11)
- 设计模式 (2)
- 搜索引擎 (1)
- 个人情感 (4)
- 笔试/面试 (3)
- 一亩三分地 (33)
- 历史 (2)
- 地理 (1)
- 人物 (3)
- 经济 (0)
- 不仅仅是笑哦 (43)
- 小故事大道理 (2)
- http://www.bjdsmyysjk120.com/ (0)
- http://www.bjdsmyy120.com/ (0)
- 它山之石可以攻玉 (15)
- 大学生你关注些什么 (28)
- 数据恢复 (1)
最新评论
-
luokaichuang:
这个规范里还是没有让我明白当浏览器上传文件时,STDIN的消息 ...
FastCGI规范 -
effort_fan:
好文章!学习了,谢谢分享!
com技术简介 -
vcell:
有错误os.walk(strPath)返回的已经是全部的文件和 ...
通过python获取目录的大小 -
feifeigd:
feifeigd 写道注意:文章中的CPP示例第二行 #inc ...
ATL入门:利用ATL编写简单的COM组件 -
feifeigd:
注意:文章中的CPP示例第二行 #include " ...
ATL入门:利用ATL编写简单的COM组件
Python:封装允许执行命令有超时的类
- 博客分类:
- python
封装允许执行命令有超时的类
#!/usr/bin/env python
import os;
import sys;
import time;
import fcntl;
import select;
import signal;
import commands;
import subprocess;
class CRunCmd:
def __init__(self):
pass;
def __AsyncRecv(self, fdSock, nMaxRead = 1024 * 8):
if not fdSock or fdSock.closed:
return (False, '')
#set fd non-block
nFlags = fcntl.fcntl(fdSock, fcntl.F_GETFL);
fcntl.fcntl(fdSock, fcntl.F_SETFL, nFlags | os.O_NONBLOCK)
bRet = False
strRead = ''
try:
#check can be read
if not select.select([fdSock], [], [], 0)[0]:
return (True, '')
strRead = fdSock.read(nMaxRead);
#if read empty, then close it
if len(strRead) <= 0:
fdSock.close();
bRet = True;
except:
bRet = False;
#reset fd
if not fdSock.closed:
fcntl.fcntl(fdSock, fcntl.F_SETFL, nFlags)
return (bRet, strRead)
def Run(self, lsCmd, nTimeOut = 0, nIntervalTime = 1):
oProc = subprocess.Popen(lsCmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
strOut = ''
strErr = '';
nStartTime = time.time()
while True:
print(oProc.poll());
if None != oProc.poll():
break;
#sleep nIntervalTime
time.sleep(nIntervalTime)
bRet, strBuf1 = self.__AsyncRecv(oProc.stdout);
bRet, strBuf2 = self.__AsyncRecv(oProc.stderr);
if len(strBuf1) > 0:
strOut += strBuf1;
if len(strBuf2) > 0:
strErr += strBuf2;
if (nTimeOut > 0) and (time.time() - nStartTime) > nTimeOut:
print("time out...");
break;
#get last buff
bRet, strBuf1 = self.__AsyncRecv(oProc.stdout);
bRet, strBuf2 = self.__AsyncRecv(oProc.stderr);
if len(strBuf1) > 0:
strOut += strBuf1;
if len(strBuf2) > 0:
strErr += strBuf2;
#if not finish, so timeout
if None == oProc.poll():
self.KillAll(oProc.pid)
return (oProc.returncode, strOut, strErr)
def KillAll(self, nKillPid, nKillSignal = signal.SIGKILL):
print("kill pid:%s" %nKillPid)
nRet, strOutput = commands.getstatusoutput('ps -A -o pid,ppid');
if 0 != nRet:
return (False, strOutput);
mapPid = {};
#make all ppid & pid map
for strLine in strOutput.split('\n'):
lsPid = strLine.strip().split();
if 2 != len(lsPid):
continue;
strPid = lsPid[0];
strPPid = lsPid[1];
if strPPid in mapPid.keys():
mapPid[strPPid].append(strPid);
else:
mapPid[strPPid] = [strPid];
#get all kill pid list
lsAllKillPid = [str(nKillPid)];
lsToKillPid = [str(nKillPid)];
while True:
if len(lsToKillPid) <= 0:
break;
lsChild = []
for strPid in lsToKillPid:
if strPid in mapPid.keys():
lsAllKillPid.extend(mapPid[strPid]);
lsChild.extend(mapPid[strPid]);
print("[%s]append:%s" %(strPid, mapPid[strPid]));
lsToKillPid = lsChild;
print("kill pid list\n%s" %lsAllKillPid)
#kill all process
for strPid in reversed(lsAllKillPid):
try:
print("kill %s" %(strPid))
#os.kill(int(strPid), nKillSignal)
except:
pass
return (True, '')
/tmp/a.py
#!/usr/bin/env python
import time;
import os;
import sys;
def Fork():
os.fork();
print("pid:%s" %os.getpid());
if '__main__' == __name__:
for i in xrange(0, int(sys.argv[1])):
print("[%s] befor fork" %os.getpid());
Fork();
print("[%s] after fork" %os.getpid());
time.sleep(1);
print("[%s] start sleep" %os.getpid());
time.sleep(10);
print("[%s] end of process..." %os.getpid());
#test code
if "__main__" == __name__:
oCmd = CRunCmd();
nRet, strOut, strErr = oCmd.Run(['python', '/tmp/a.py', '10'], 5)
print("ret:%s" %nRet);
print("stdout:%s" %strOut);
print("stderr:%s" %strErr);
执行结果:
$python w_p.py
None
None
None
None
None
time out...
kill pid:29443
[29443]append:['29444', '29446', '29450', '29457', '29474']
[29444]append:['29445', '29448', '29454', '29463']
[29446]append:['29449', '29456', '29465']
[29450]append:['29458', '29471']
[29457]append:['29473']
[29445]append:['29447', '29452', '29462']
[29448]append:['29453', '29461']
[29454]append:['29470']
[29449]append:['29455', '29468']
[29456]append:['29467']
[29458]append:['29472']
[29447]append:['29451', '29466']
[29452]append:['29459']
[29453]append:['29460']
[29455]append:['29469']
[29451]append:['29464']
kill pid list
['29443', '29444', '29446', '29450', '29457', '29474', '29445', '29448', '29454', '29463', '29449', '29456', '29465', '29458', '29471', '29473', '29447', '29452', '29462', '29453', '29461', '29470', '29455', '29468', '29467', '29472', '29451', '29466', '29459', '29460', '29469', '29464']
kill 29464
kill 29469
kill 29460
kill 29459
kill 29466
kill 29451
kill 29472
kill 29467
kill 29468
kill 29455
kill 29470
kill 29461
kill 29453
kill 29462
kill 29452
kill 29447
kill 29473
kill 29471
kill 29458
kill 29465
kill 29456
kill 29449
kill 29463
kill 29454
kill 29448
kill 29445
kill 29474
kill 29457
kill 29450
kill 29446
kill 29444
kill 29443
ret:None
stdout:
stderr:
发表评论
-
提供有偿反编译 python2.5,2.6,2.7 code
2014-04-03 16:32 1276提供有偿 反编译 python2.5, python2.6 ... -
Python 多线程编程及同步处理
2011-06-17 13:04 3046综述 多线程是程序设计中的一个重要方面,尤其是 ... -
python 去掉重复行
2011-06-16 12:15 6834#!/usr/bin/env python impor ... -
通过python获取目录的大小
2011-06-07 11:04 8862通过python获取目录的大小 需要用到的mod ... -
python 单元测试示例2
2011-05-17 11:51 1512#!/usr/bin/env python ... -
python 单元测试示例1
2011-05-17 11:51 1703#!/usr/bin/env python im ... -
python 获取文件md5
2011-05-13 14:01 7986#!/usr/bin/env python im ... -
python模拟windows获取设置ini
2011-05-05 12:20 1088#!/usr/bin/env python from ... -
python 解析 json
2011-04-25 15:42 3647#!/usr/bin/env python impor ... -
python时间处理
2011-04-23 19:25 674import time; import os; impor ... -
python简单的socket 服务器和客户端
2011-03-03 17:42 11489服务器端代码 if "__main__&qu ... -
python __file__ 与argv[0]
2011-02-28 11:25 36735python __file__ 与argv[0] 在py ... -
python os.path模块 简明文档
2011-02-28 11:10 2054os.path.abspath(path)取path的绝对目录 ... -
Python 用HTMLParser解析HTML文件
2011-02-16 20:44 34916Python 用HTMLParser解析HTML文件 ... -
python使用simplejson解析示例
2011-02-16 15:28 8160#!/usr/bin/env python imp ... -
python simplejson模块的使用方法
2011-02-16 14:38 10280python安装:easy_install simplejso ... -
用PDB库调试Python程序
2011-01-06 12:54 1895如果使用过微软技术的朋友应该体会过微软的Visual Stud ... -
python更新svn
2010-12-29 11:05 6265def UpdateSvn(strUser, strPwd, ... -
python 函数参数的传递(参数带星号的说明)
2010-12-23 17:59 1393python中函数参数的传递是通过赋值来传递的。函数参数的 ... -
python 之 分割参数getopt
2010-12-17 11:02 51322python 之 分割参数getopt ...
相关推荐
可以有或者没有接收超时。 类似文件的API,例如read和write,也支持readline等。 支持二进制传输,没有null消除,没有cr-lf转换。 有关Python的环境配置请参考: 《Python入门》Windows 7下Python Web开发环境搭建...
paramiko是python的SSH库,可用来连接远程linux主机,然后执行linux命令或者通过SFTP传输文件。 关于使用paramiko执行远程主机命令可以找到很多参考资料了,本文在此基础上做一些封装,便于扩展与编写脚本。 下面...
主要介绍了详解Python requests 超时和重试的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
Qt 以阻塞的方式调用 Python 函数,所以直接在函数中执行网络IO是不可行的(等待响应的过程用户界面会失去响应),所以这里使用 qasync 模块兼容了 Python 的异步框架 asyncio。通过这种方法,所有阻塞操作全部可以...
今天小编就为大家分享一篇python 通过SSHTunnelForwarder隧道连接redis的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 背景:我司Redis服务器使用的亚马逊服务,本地需要通过跳板机,然后...
YaSQL简介YaSQL是MySQL / TiDB的数据库审核执行平台,逐步降低了DBA的运维成本,...工单可以在各个环境内自由钩MySQL DDL ALTER语句自动使用gh-ost改表DML语句执行,支持获取锁定超时,事务封装,自动开启严格模式执行
1.纯python实现,跨平台 2.自动重连接 3.可靠发送–可配置的消息方式与消息超时方式 4.持久化/临时 两种队列 5.支持异步 — poll() 6.symmetrical — 单个TCP连接可用于双工通讯 7.多数据库支持 — SQLite、MongoDB...
Python源代码(CPython,注意不是Cython),多少次遇到百思不得其解的问题,我都是去看看Python是怎么封装成简单可靠的接口的,比如我回答Linux TCP connect with Select() fails at testserver,还有怎么实现一个...
整个项目的后端是基于Python的,用到了Flask、Pandas、SqlAlchemy。 Flask AppBuilder(鉴权、CRUD、规则 Pandas(分析) SqlAlchemy(数据库ORM) 此外,也关注到Superset的缓存机制值得我们学习: 采用...
充分利用了python的特性,如对象协议、元类、混入类mixin、列表推导式、生成器 对参数的接收采用了flask_restful的reqparse思想,使得代码精简了很多 考虑了设计模式,如工厂方法 增加了oss连接超时处理 引入了请求...
一、简介 RobotFrameWork是完全基于Python实现的开源的自动化测试框架,RF已经封装好的各个模块,基于关键字驱动的形式来实现的自动化测试。其case采用表格形式易读,且支持BDD,可容纳各种外置库,可以继承Selenium...