プロセスが異常終了するか、まったく終了しない場合でも、その時点までに生成された可能性のある出力を収集できるようにしたいと考えています。
このコード例の明白な解決策は、os.kill で子プロセスを強制終了することですが、私の実際のコードでは、子プロセスは NFS を待ってハングし、SIGKILL に応答しません。
#!/usr/bin/python
import subprocess
import os
import time
import signal
import sys
child_script = """
#!/bin/bash
i=0
while [ 1 ]; do
echo "output line $i"
i=$(expr $i \+ 1)
sleep 1
done
"""
childFile = open("/tmp/childProc.sh", 'w')
childFile.write(child_script)
childFile.close()
cmd = ["bash", "/tmp/childProc.sh"]
finish = time.time() + 3
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
while p.poll() is None:
time.sleep(0.05)
if finish < time.time():
print "timed out and killed child, collecting what output exists so far"
out, err = p.communicate()
print "got it"
sys.exit(0)
この場合、タイムアウトに関する print ステートメントが表示され、python スクリプトは終了または進行しません。これを別の方法で実行し、子プロセスから出力を取得する方法を知っている人はいますか