python中out_在python中,如何在subprocess*中使用timeout并*获取outpu

我用了这两个问题的密码

得到了这个import subprocess, threading, os

class ThreadWithReturnValue(threading.Thread):

def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None):

threading.Thread.__init__(self, group, target, name, args, kwargs, Verbose)

self._return = None

def run(self):

if self._Thread__target is not None:

self._return = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)

def join(self, timeout = None):

threading.Thread.join(self, timeout)

return self._return

class SubprocessWrapper(object):

def __init__(self, cmd, timeout):

self.cmd = cmd

self.process = None

self.timeout = timeout

def run(self):

def target(cmd):

self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr = subprocess.PIPE)

returnValue = self.process.communicate()

return [returnValue[0], returnValue[1], self.process.returncode]

thread = ThreadWithReturnValue(target=target, args=[self.cmd])

thread.start()

returnValue = thread.join(self.timeout)

if thread.is_alive():

print 'cmd = ',self.cmd

self.process.kill()

returnValue = thread.join()

print 'rc = ', returnValue[2]

output = returnValue[0]

error = returnValue[1]

rc = returnValue[2]

return (output, rc)

os.system('date +%T.%N')

s1 = SubprocessWrapper("echo 'Process started'; sleep 2; echo 'Process finished'", timeout = 3)

s1.run()

os.system('date +%T.%N')

s2 = SubprocessWrapper("echo 'Process started'; sleep 2; echo 'Process finished'", timeout = 1)

s2.run()

os.system('date +%T.%N')

问题是输出是

^{pr2}$

所以你可以看到,原本应该在一秒钟后终止的进程实际上花了2秒。这是因为join()的缘故,但在问题subprocess with timeout中,这很好。这意味着,当我整合了这两个代码时,我的问题是如何解决它?我在想我可能需要以不同的方式调用threading.Thread.__init__方法,但我不明白如何调用。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值