python 解决os.popen 超时问题
🕔 by pyList at 2015-07-02 16:21
Python 使用函数 os.popen 会出现过长时间等待导致阻塞问题。
解决方法如下:
def TIMEOUT_COMMAND(command, timeout):
"""call shell-command and either return its output or kill it
if it doesn't normally exit within timeout seconds and return None"""
import subprocess, datetime, os, time, signal
cmd = command.split(" ")
start = datetime.datetime.now()
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while process.poll() is None:
time.sleep(0.2)
now = datetime.datetime.now()
if (now - start).seconds> timeout:
os.kill(process.pid, signal.SIGKILL)
os.waitpid(-1, os.WNOHANG)
return None
return process.stdout.readlines()
循环
忙等 子进程结束
import subprocess
import os
import time
tt = '555'
cmd = "python /home/100003/python/mypython/sub2.py "+" 333"+" 444 "+tt
print time.time()
sub2 = subprocess.Popen(cmd, shell=True)
while 1:
ret1 = subprocess.Popen.poll(sub2)
if ret1 == 0:
print sub2.pid,'end'
break
elif ret1 is None:
print 'running'
time.sleep(1)
else:
print sub2.pid,'term'
break
print time.time()
子进程结束
立即返回 使用select模块 同时可设置子进程的超时时间
import subprocess
import select
import time
import signal
import os
tt = '555'
cmd = "python /home/100003/python/mypython/sub2.py "+" 333"+" 444 "+tt
timeout = 3
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,shell = True)
print time.time()
while 1:
while_begin = time.time()
print 'timeout',timeout
fs = select.select([pro.stdout], [], [], timeout)
if pro.stdout in fs[0]:
tmp = pro.stdout.read()
print 'read', tmp
if not tmp:
print 'end'
print time.time()
break
else:
print 'outoftime'
print os.kill(pro.pid, signal.SIGKILL),
break
timeout = timeout - (time.time() - while_begin)
import subprocess, threading
class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None
def run(self, timeout):
def target():
print 'Thread started'
self.process = subprocess.Popen(self.cmd, shell=True)
self.process.communicate()
print 'Thread finished'
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print 'Terminating process'
self.process.terminate()
thread.join()
print self.process.returncode
command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")
command.run(timeout=3)
command.run(timeout=1)
Thread started
Process started
Process finished
Thread finished
0
Thread started
Process started
Terminating process
Thread finished
-15
如果数unix 系统
import signal
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
...
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(5*60) # 5 minutes
try:
stdoutdata, stderrdata = proc.communicate()
signal.alarm(0) # reset the alarm
except Alarm:
print "Oops, taking too long!"
# whatever else
本文网址: https://pylist.com/t/1435825308 (转载注明出处)
如果你有任何建议或疑问可以在下面 留言
发表第一条评论!
相关推荐
小工具
标签
python
时间
判断
当前
是否
字符串
随机
生成
颜色
12
基础知识
编程
总结
sae
pil
image
高质量
轻量级
博客
一款
解析
电子书
信息
转码
链接
中文
安全
分割
英文
mail
gmail
发送
files
mac
open
解决
办法
xor
解密
加密
方法
u盘
diskutil
格式化
顽固
之坑
golang
服务
app
store
登录
未知
xmltodict
gbk
xml
编码
openwrt
usb
上网卡
共享
网络
bbr
路由
开启
sqlite
数据库
提速
经验
固件
debian
ubuntu
编译
系统启动
硬件加速
ubnt
er
最新版
wndr4300
升级
访问速度
vps
加速
js
fonts
css
html
一键
后缀名
并取
遍历
文件夹
failed
load
devtools
sourcemap
chrome
自动更新
microsoft
关闭
静音
风扇
主机
笔记本
改造
低功耗
web
爬虫
服务器
组装
微信
尝鲜
视频
体验
cpu
查看
温度
server
浏览
google
身份验证
authenticator
迁移
手机
webdriver
微博
selenium
gnu
linux
安装
宅家
坑记
屏幕
动手
nginx
quic
抢先
最近发表
- Chrome 控制台 DevTools failed to load SourceMap 警告的消除方法
- Mac 关闭 Microsoft 自动更新
- Mac 登录 App Store 出现“发生了未知错误”的解决方法
- 老笔记本改造为无风扇静音主机方案
- 自己组装21瓦低功耗家庭爬虫、文件、web服务器
- 微信视频号尝鲜体验
- Ubuntu/Debian 查看CPU温度的方法
- 在Ubuntu/debian Server 系统使用Chrome 无头浏览模式
- 换手机后 Google 身份验证器 Google Authenticator 数据迁移的简单方法
- 使用Golang selenium WebDriver 自动登录微博
- 在 Ubuntu 或其它 GNU/Linux 系统下安装 Debian
- Mac 下制作 USB ubuntu/debian 系统启动、安装盘的几种方法
- ubuntu/debian 下自行编译 OpenWRT 固件
- 宅家自己动手换手机屏幕掉坑记
- 路由 UBNT ER-X 官方固件升级及开启硬件加速的方法
- 在 Nginx 和 Golang web 上抢先体验 QUIC
最近浏览
- 用python 实现XOR 加密解密的方法
- 在终端使用Mac diskutil 命令格式化顽固U盘
- Golang 服务之坑:too many open files
- Mac 登录 App Store 出现“发生了未知错误”的解决方法
- python xmltodict 解析xml gbk 编码问题解决
- Openwrt 使用USB 4G 上网卡共享网络
- Openwrt 路由上开启BBR
- python SQLite 数据库提速经验
- ubuntu/debian 下自行编译 OpenWRT 固件
- Mac 下制作 USB ubuntu/debian 系统启动、安装盘的几种方法
- 路由 UBNT ER-X 官方固件升级及开启硬件加速的方法
- WNDR4300 固件升级到 OpenWrt 最新版
- 开启BBR 加速小VPS访问速度
- 一键下载网站资源(html/css/js/fonts)
- python 分割中文英文混合字符串的正确方法
- 编写python脚本遍历文件夹并取指定后缀名文件