这是我的日志

File "/opt/ibm/db2-governor/helpers/utils.py", line 10, in run_cmd
output = proc.communicate(timeout = timeout)[0]
  File "/opt/ibm/dynamite/python/lib/python2.7/site-packages/subprocess32.py", line 927, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "/opt/ibm/dynamite/python/lib/python2.7/site-packages/subprocess32.py", line 1713, in _communicate
    orig_timeout)
  File "/opt/ibm/dynamite/python/lib/python2.7/site-packages/subprocess32.py", line 1786, in _communicate_with_poll
    ready = poller.poll(self._remaining_time(endtime))
OverflowError: Python int too large to convert to C lon


所以触发这个的代码是

output = proc.communicate(timeout = timeout)[0]


超时设置为20,这是间歇性发生的(几乎从不发生,但是会发生),即时通讯将python 2.7.11与subprocess32库一起使用,这是python的错误吗?

好的,我检查了subprocess32.py,这行是这样的

endtime = time.time() + timeout

ready = poller.poll(self._remaining_time(endtime))


所以基本上时间戳太大了,无法转换为c int,有什么我可以解决的吗?

最佳答案

听起来像个虫子。

如果您有兴趣,这里有一个解决方法:不使用communicate,而是在线程中读取进程stdout,然后检查进程是否结束了,以便通过poll读取或返回代码产量。

由于控制了循环,因此您可以在主线程中等待1秒钟,然后等待超时(由于sleep可能会漂移,因此不太准确,但这足够好且简单)。当达到0时也杀死进程。

import threading

output = ""

def subp(p):
    global output

    while True:
        # read blocks but since we're in a thread it doesn't matter
        data = proc.stdout.read()
        if not data or proc.poll() != None:
            break
        output += data

# here create the process
proc = subprocess...

# create a thread, pass the process handle
t = threading.Thread(target=subp,args=(proc,))

while True:
    if proc.poll() != None:
      # exit: OK
      break
    timeout -= 1
    if timeout < 0:
        # took too long: kill
        proc.terminate()
        break
    time.sleep(1)

t.join()

10-02 08:50