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
我只找到了使用单独脚本打开子进程的文档。有谁知道如何传递函数对象甚至是一种简单的方法来传递函数代码?
答案 0 :(得分:79)
我认为你正在寻找更像多处理模块的东西:
http://docs.python.org/library/multiprocessing.html#the-process-class
子进程模块用于生成进程并使用其输入/输出进行操作 - 而不是用于运行函数。
以下是您的代码的multiprocessing
版本:
from multiprocessing import Process, Queue
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
答案 1 :(得分:13)
您可以使用标准的Unix fork
系统调用,os.fork()
。 fork()
将创建一个新进程,并运行相同的脚本。在新进程中,它将返回0,而在旧进程中,它将返回新进程的进程ID。
child_pid = os.fork()
if child_pid == 0:
print "New proc"
else:
print "Old proc"
对于更高级别的库,它提供了多处理支持,为使用多个进程提供了可移植的抽象,那就是multiprocessing模块。有一篇关于IBM DeveloperWorks的文章Multiprocessing with Python,其中简要介绍了这两种技术。
答案 2 :(得分:5)
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)
功能立即设置线程。