私は Daniel G. answer に触発され、非常に単純なユース ケースを実装しました。私の仕事では、同じ (外部) プロセスを異なる引数で繰り返し呼び出す必要があることがよくあります。特定の呼び出しがいつ行われたかを判断する方法をハックしましたが、今ではコールバックを発行するためのよりクリーンな方法があります。
この実装は非常にシンプルで気に入っていますが、複数のプロセッサに非同期呼び出しを発行し (multiprocessing
の代わりに使用していることに注意してくださいthreading
)、完了時に通知を受け取ることができます。
サンプル プログラムをテストしたところ、問題なく動作しました。自由に編集してフィードバックをお寄せください。
import multiprocessing
import subprocess
class Process(object):
"""This class spawns a subprocess asynchronously and calls a
`callback` upon completion; it is not meant to be instantiated
directly (derived classes are called instead)"""
def __call__(self, *args):
# store the arguments for later retrieval
self.args = args
# define the target function to be called by
# `multiprocessing.Process`
def target():
cmd = [self.command] + [str(arg) for arg in self.args]
process = subprocess.Popen(cmd)
# the `multiprocessing.Process` process will wait until
# the call to the `subprocess.Popen` object is completed
process.wait()
# upon completion, call `callback`
return self.callback()
mp_process = multiprocessing.Process(target=target)
# this call issues the call to `target`, but returns immediately
mp_process.start()
return mp_process
if __name__ == "__main__":
def squeal(who):
"""this serves as the callback function; its argument is the
instance of a subclass of Process making the call"""
print "finished %s calling %s with arguments %s" % (
who.__class__.__name__, who.command, who.args)
class Sleeper(Process):
"""Sample implementation of an asynchronous process - define
the command name (available in the system path) and a callback
function (previously defined)"""
command = "./sleeper"
callback = squeal
# create an instance to Sleeper - this is the Process object that
# can be called repeatedly in an asynchronous manner
sleeper_run = Sleeper()
# spawn three sleeper runs with different arguments
sleeper_run(5)
sleeper_run(2)
sleeper_run(1)
# the user should see the following message immediately (even
# though the Sleeper calls are not done yet)
print "program continued"
出力例:
program continued
finished Sleeper calling ./sleeper with arguments (1,)
finished Sleeper calling ./sleeper with arguments (2,)
finished Sleeper calling ./sleeper with arguments (5,)
sleeper.c
以下は、私のサンプル「時間のかかる」外部プロセスのソースコードです
#include<stdlib.h>
#include<unistd.h>
int main(int argc, char *argv[]){
unsigned int t = atoi(argv[1]);
sleep(t);
return EXIT_SUCCESS;
}
次のようにコンパイルします。
gcc -o sleeper sleeper.c