2

A と B という 2 つの関数を持つ MyScript という Python スクリプト (RHEL ベースの UNIX ライク) があります。異なる独立したプロセス (B と A を切り離す) でそれらを実行したいと思います。

  • スクリプトの開始 MyScript
  • 機能Aを実行
  • 新しいプロセスを生成し、関数 A から B にデータを渡します
  • 関数 B の実行中に関数 A を続行する
  • 関数 A が完了したら、B がまだ実行中であっても MyScript を終了します。

マルチプロセッシングを使用してデーモン プロセスを作成する必要があると考えましたが、ドキュメントによると、それは適切なユースケースではありません。そこで、子プロセスと子 ^2 プロセス (子の子) を生成し、子を強制的に終了させることにしました。この回避策は機能しているように見えますが、実際には醜いようです。

もっとpythonicにするのを手伝ってくれませんか?subprocess モジュールには、関数を操作するメソッドがありますか? 以下サンプルコード。

import multiprocessing
import time
import sys
import os

def parent_child():
    p = multiprocessing.current_process()
    print 'Starting parent child:', p.name, p.pid
    sys.stdout.flush()
    cc = multiprocessing.Process(name='childchild', target=child_child)
    cc.daemon = False
    cc.start()
    print 'Exiting parent child:', p.name, p.pid
    sys.stdout.flush()

def child_child():
    p = multiprocessing.current_process()
    print 'Starting child child:', p.name, p.pid
    sys.stdout.flush()
    time.sleep(30)
    print 'Exiting child child:', p.name, p.pid
    sys.stdout.flush()

def main():
    print 'starting main', os.getpid()
    d = multiprocessing.Process(name='parentchild', target=parent_child)
    d.daemon = False
    d.start()
    time.sleep(5)
    d.terminate()
    print 'exiting main', os.getpid()

main()
4

1 に答える 1

2

これは、機能を単一の呼び出しに移動する、元のコードのランダム バージョンですspawn_detached(callable)。プログラムが終了した後でも、切り離されたプロセスを実行し続けます。

import time
import os
from multiprocessing import Process, current_process

def spawn_detached(callable):
    p = _spawn_detached(0, callable)
    # give the process a moment to set up
    # and then kill the first child to detach
    # the second.
    time.sleep(.001)
    p.terminate()

def _spawn_detached(count, callable):
    count += 1
    p = current_process()
    print 'Process #%d: %s (%d)' % (count, p.name, p.pid)

    if count < 2:
        name = 'child'
    elif count == 2:
        name = callable.func_name
    else:
        # we should now be inside of our detached process
        # so just call the function
        return callable()

    # otherwise, spawn another process, passing the counter as well
    p = Process(name=name, target=_spawn_detached, args=(count, callable)) 
    p.daemon = False 
    p.start()
    return p

def operation():
    """ Just some arbitrary function """
    print "Entered detached process"
    time.sleep(15)
    print "Exiting detached process"


if __name__ == "__main__":
    print 'starting main', os.getpid()
    p = spawn_detached(operation)
    print 'exiting main', os.getpid()
于 2012-10-27T02:13:51.177 に答える