65

私は現在、を使用してプログラムを起動していますsubprocess.Popen(cmd, shell=TRUE)

私はPythonにかなり慣れていませんが、次のようなことを実行できるAPIがあるはずだと「感じています」。

subprocess.Popen(cmd, shell=TRUE,  postexec_fn=function_to_call_on_exit)

私はこれを行っているのでfunction_to_call_on_exit、cmdが終了したことを知っていることに基づいて何かを行うことができます(たとえば、現在実行中の外部プロセスの数をカウントし続ける)

スレッドとメソッドを組み合わせたクラスでサブプロセスをかなり簡単にラップできるとPopen.wait()思いますが、Pythonでスレッドをまだ実行しておらず、APIが存在するのに十分一般的であると思われるため、最初に1つ見つけてみてください。

前もって感謝します :)

4

8 に答える 8

74

おっしゃる通りです。これに適した API はありません。2 番目の点も正しいです。スレッドを使用してこれを行う関数を設計するのは簡単です。

import threading
import subprocess

def popen_and_call(on_exit, popen_args):
    """
    Runs the given args in a subprocess.Popen, and then calls the function
    on_exit when the subprocess completes.
    on_exit is a callable object, and popen_args is a list/tuple of args that 
    would give to subprocess.Popen.
    """
    def run_in_thread(on_exit, popen_args):
        proc = subprocess.Popen(*popen_args)
        proc.wait()
        on_exit()
        return
    thread = threading.Thread(target=run_in_thread, args=(on_exit, popen_args))
    thread.start()
    # returns immediately after the thread starts
    return thread

Python ではスレッド化も非常に簡単ですが、on_exit() の計算コストが高い場合は、マルチプロセッシングを使用する代わりに、これを別のプロセスに配置する必要があることに注意してください (GIL によってプログラムの速度が低下しないようにするため)。それは実際には非常に単純です。(ほぼ) 同じ API に従っているため、基本的にすべての呼び出しをthreading.Threadに置き換えるだけで済みます。multiprocessing.Process

于 2010-04-06T00:27:04.740 に答える
21

Python 3.2 にはconcurrent.futuresモジュールがあります (pip install futures古い Python < 3.2 で利用可能):

pool = Pool(max_workers=1)
f = pool.submit(subprocess.call, "sleep 2; echo done", shell=True)
f.add_done_callback(callback)

コールバックは、 を呼び出したのと同じプロセスで呼び出されf.add_done_callback()ます。

フルプログラム

import logging
import subprocess
# to install run `pip install futures` on Python <3.2
from concurrent.futures import ThreadPoolExecutor as Pool

info = logging.getLogger(__name__).info

def callback(future):
    if future.exception() is not None:
        info("got exception: %s" % future.exception())
    else:
        info("process returned %d" % future.result())

def main():
    logging.basicConfig(
        level=logging.INFO,
        format=("%(relativeCreated)04d %(process)05d %(threadName)-10s "
                "%(levelname)-5s %(msg)s"))

    # wait for the process completion asynchronously
    info("begin waiting")
    pool = Pool(max_workers=1)
    f = pool.submit(subprocess.call, "sleep 2; echo done", shell=True)
    f.add_done_callback(callback)
    pool.shutdown(wait=False) # no .submit() calls after that point
    info("continue waiting asynchronously")

if __name__=="__main__":
    main()

出力

$ python . && python3 .
0013 05382 MainThread INFO  begin waiting
0021 05382 MainThread INFO  continue waiting asynchronously
done
2025 05382 Thread-1   INFO  process returned 0
0007 05402 MainThread INFO  begin waiting
0014 05402 MainThread INFO  continue waiting asynchronously
done
2018 05402 Thread-1   INFO  process returned 0
于 2011-03-06T09:43:22.350 に答える
16

でキーワード引数を使用したかったので、別のタプル/リストとしてではなく、単にsubprocess.Popen argsandをそのまま渡すように Daniel G の回答を変更しました。kwargssubprocess.Popen

私の場合、postExec()実行したいメソッドがありましたsubprocess.Popen('exe', cwd=WORKING_DIR)

以下のコードでは、単純にpopenAndCall(postExec, 'exe', cwd=WORKING_DIR)

import threading
import subprocess

def popenAndCall(onExit, *popenArgs, **popenKWArgs):
    """
    Runs a subprocess.Popen, and then calls the function onExit when the
    subprocess completes.

    Use it exactly the way you'd normally use subprocess.Popen, except include a
    callable to execute as the first argument. onExit is a callable object, and
    *popenArgs and **popenKWArgs are simply passed up to subprocess.Popen.
    """
    def runInThread(onExit, popenArgs, popenKWArgs):
        proc = subprocess.Popen(*popenArgs, **popenKWArgs)
        proc.wait()
        onExit()
        return

    thread = threading.Thread(target=runInThread,
                              args=(onExit, popenArgs, popenKWArgs))
    thread.start()

    return thread # returns immediately after the thread starts
于 2012-05-30T20:39:33.257 に答える
7

私は同じ問題を抱えていて、それを使用して解決しmultiprocessing.Poolました。関連する 2 つのハッキーなトリックがあります。

  1. プールのサイズを 1 にする
  2. 長さ 1 の iterable 内で iterable 引数を渡す

結果は、完了時にコールバックで実行される 1 つの関数です

def sub(arg):
    print arg             #prints [1,2,3,4,5]
    return "hello"

def cb(arg):
    print arg             # prints "hello"

pool = multiprocessing.Pool(1)
rval = pool.map_async(sub,([[1,2,3,4,5]]),callback =cb)
(do stuff) 
pool.close()

私の場合、呼び出しもノンブロッキングにしたかったのです。美しく動作します

于 2011-01-08T23:03:53.657 に答える
2

私は 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
于 2011-03-06T07:14:22.537 に答える
-1

私の知る限り、少なくともsubprocessモジュールにはそのような API はありません。おそらくスレッドを使用して、自分で何かを転がす必要があります。

于 2010-04-05T23:52:26.013 に答える