2

私は現在、いくつかのWebタスクを自動化するためにPythonモジュールSpynnerを使用しています。私は問題に遭遇しましたが、何らかの理由でプロセスが単に移動を停止し、フリーズしますが、Windowsによると応答します。

私がやりたいのは、これが発生するかどうかを確認するために何らかの形のモニターをセットアップしてから、プロセスを再開することです。プログラムの端末出力を監視することを考えていたのですが、一定時間後にデータのプッシュを停止すると、プログラムが強制終了して再起動します。

osとサブプロセスを使用して、プログラムを強制終了して再実行する方法はわかっていますが、ターミナルが特定の時間データの送信を停止するかどうかを監視するようにピースを設定する方法がわかりません。

4

1 に答える 1

5

次のコードは、「 Pythonのsubprocess.PIPEでのノンブロッキング読み取り」から借用され、わずかに変更されています(kudos to JF Sebastian-この回答を受け入れる場合は、元のコードに賛成してください)

import sys
import time
from subprocess import PIPE, Popen
from threading  import Thread

try:
    from Queue import Queue, Empty
except ImportError:
    from queue import Queue, Empty  # python 3.x

ON_POSIX = 'posix' in sys.builtin_module_names

def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        timestamp = time.time( )
        queue.put((timestamp, line))
    out.close()

#-- This is how long you're willing to wait before you 
#-- consider your Spynner process to be brain-dead.
MAX_WAIT_TIME = 300.0  #-- we'll wait 5 minutes (300 seconds)

#-- Construct a shared queue that will be used to send messages from 
#-- the subprocess I/O polling thread to the watchdog (main) thread.
q = Queue()

#-- Spawn your subprocess...
p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)

#-- Create a new thread that runs in the same process as the watchdog.
#-- This thread will poll the output of the subprocess and populate the 
#-- shared queue.
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()

#-- Now, we'll try to read from the shared queue.
try:
    #-- Queries the shared queue for the next item in the queue,
    #-- waiting for up to MAX_WAIT_TIME before failing with an Empty exception.
    timestamp, line = q.get(True, MAX_WAIT_TIME)
except Empty:
    #-- Ok...the queue is empty and it's been MAX_WAIT_TIME since
    #-- We've pulled anything from the queue.
    p.terminate( )  #-- "terminate with extreme prejudice"
else: # got line
    #-- Got a (timestamp, line_of_text) pair, where the timestamp is the
    #-- system time when the I/O polling thread grabbed the line from
    #-- the subprocess pipe.  This timestamp isn't strictly necessary,
    #-- but might come in handy in debugging the brain-dead Spynner process.
    #-- So now...do something with that line of text!
    doSomething(line)

新しいSpynnerプロセスを生成して、終了したプロセスが中断したところをピックアップするためのロジックを使用してこのコードを拡張する必要がありますが、これにより、続行する方法がわかるはずです。

于 2012-05-10T05:33:33.183 に答える