可以在子进程中运行函数而不使用线程或单独文件/脚本吗?
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 个回答
9
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)
这个功能,来让线程立即在后台运行。
24
你可以使用标准的Unix系统调用fork
,在Python中可以用os.fork()
来实现。fork()
会创建一个新的进程,新的进程会运行相同的脚本。在新进程中,它会返回0,而在旧的进程中,它会返回新进程的ID。
child_pid = os.fork()
if child_pid == 0:
print "New proc"
else:
print "Old proc"
如果你想要一个更高级的库,可以使用支持多进程的multiprocessing
模块,它提供了一个便于使用多个进程的跨平台抽象。IBM DeveloperWorks上有一篇文章,用Python进行多进程编程,简单介绍了这两种技术。
141
我觉得你可能在寻找更像是多进程模块的东西:
http://docs.python.org/library/multiprocessing.html#the-process-class
子进程模块是用来创建进程并处理它们的输入/输出的,而不是用来运行函数的。
这是你代码的一个 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