92
import subprocess

def my_function(x):
    return x + 100

output = subprocess.Popen(my_function, 1) #I would like to pass the function object and its arguments
print output 
#desired output: 101

別のスクリプトを使用してサブプロセスを開くことに関するドキュメントしか見つかりませんでした。関数オブジェクトを渡す方法、または関数コードを渡す簡単な方法を知っている人はいますか?

4

3 に答える 3

123

multiprocessing モジュールのようなものを探していると思います:

http://docs.python.org/library/multiprocessing.html#the-process-class

subprocess モジュールは、プロセスを生成し、その入出力を処理するためのものであり、関数を実行するためのものではありません。

コードのmultiprocessingバージョンは次のとおりです。

from multiprocessing import Process, Queue

# must be a global function    
def my_function(q, x):
    q.put(x + 100)

if __name__ == '__main__':
    queue = Queue()
    p = Process(target=my_function, args=(queue, 1))
    p.start()
    p.join() # this blocks until the process terminates
    result = queue.get()
    print result
于 2010-01-12T03:57:13.867 に答える
20

として、標準の Unixforkシステム コールを使用できますos.fork()fork()同じスクリプトを実行して、新しいプロセスを作成します。新しいプロセスでは 0 を返しますが、古いプロセスでは新しいプロセスのプロセス ID を返します。

child_pid = os.fork()
if child_pid == 0:
  print "New proc"
else:
  print "Old proc"

複数のプロセスを使用するための移植可能な抽象化を提供する multiprocessing サポートを提供する高レベルのライブラリには、multiprocessingモジュールがあります。IBM DeveloperWorks に関する記事Multiprocessing with Pythonで、両方の手法を簡単に紹介しています。

于 2010-01-12T03:58:47.570 に答える
8

マルチプロセッシングに関する Brian McKenna の上記の投稿は非常に役に立ちますが、(プロセスベースではなく) スレッド化されたルートをたどりたい場合は、次の例を参考にしてください。

import threading
import time

def blocker():
    while True:
        print "Oh, sorry, am I in the way?"
        time.sleep(1)

t = threading.Thread(name='child procs', target=blocker)
t.start()

# Prove that we passed through the blocking call
print "No, that's okay" 

この機能を使用してsetDaemon(True)、スレッドをすぐにバックグラウンドにすることもできます。

于 2014-08-06T22:02:24.883 に答える