Posted on 2013-05-10 21:26
Onway 閱讀(2767)
評論(0) 編輯 收藏 引用 所屬分類:
碼兒快跑
python程序里面需要執(zhí)行一個(gè)系統(tǒng)命令程序,如果命令在限定時(shí)間之內(nèi)結(jié)束,則python程序讀取其輸出(如果有)并馬上返回,否則強(qiáng)行終止命令程序。
原本這個(gè)功能是用系統(tǒng)信號SIGALARM和python的異常解決的,但這不能用在多線程的環(huán)境里。然后考慮用threading.Timer進(jìn)行計(jì)時(shí),但這個(gè)計(jì)時(shí)是在一個(gè)單獨(dú)線程進(jìn)行的,如何將超時(shí)信息傳給主線程也是一個(gè)問題。
百度一下,用select可以解決需求:
但select并不完美,當(dāng)命令程序輸出的內(nèi)容多于管道容量的時(shí)候,select就會(huì)返回,如果此時(shí)命令程序再進(jìn)入阻塞,則時(shí)間限制就不起作用了。
select.py:
import select
import subprocess
popen = subprocess.Popen("./test.sh", stdout=subprocess.PIPE)
fs = select.select([popen.stdout], [], [], 3)
if popen.stdout in fs[0]:
output = popen.stdout.read()
print len(output)
else:
print "timeout"
test.sh:
#!/bin/bash
# a.txt contains 65536 characters
cat a.txt
sleep 10
cat a.txt