且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在没有线程或编写单独的文件/脚本的情况下在子进程中运行函数。

更新时间:2023-09-12 18:06:40

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