是否可以在没有线程或编写单独的文件/脚本的情况下在子进程中运行函数。 [英] Is it possible to run function in a subprocess without threading or writing a separate file/script.
问题描述
import subprocess
def my_function(x):
return x + 100
output = subprocess.Popen( my_function,1)#我想传递函数对象及其参数
print输出
#desired输出:101
我只找到使用单独脚本打开子过程的文档。有没有人知道如何传递函数对象,甚至传递函数代码的简单方法?
我认为你正在寻找更像是多处理模块:
http://docs.python.org/library/multiprocessing.html#the-process-class
子流程模块用于产卵过程和处理它们的输入/输出 - 而不是运行函数。
这是一个多处理
版本的你的代码:
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 =(队列,1))
p.start()
p.join()#这会阻塞,直到进程终止
result = queue.get()
print结果
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
I have only found documentation on opening subprocesses using separate scripts. Does anyone know how to pass function objects or even an easy way to pass function code?
I think you're looking for something more like the multiprocessing module:
http://docs.python.org/library/multiprocessing.html#the-process-class
The subprocess module is for spawning processes and doing things with their input/output - not for running functions.
Here is a multiprocessing
version of your code:
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
这篇关于是否可以在没有线程或编写单独的文件/脚本的情况下在子进程中运行函数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!