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
我只找到了使用单独脚本打开子进程的文档。有人知道如何传递函数对象或者甚至是传递函数代码的简便方法吗?
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
我只找到了使用单独脚本打开子进程的文档。有人知道如何传递函数对象或者甚至是传递函数代码的简便方法吗?
我认为你更需要的是类似于multiprocessing模块的东西:
http://docs.python.org/library/multiprocessing.html#the-process-class
subprocess模块用于生成进程并处理它们的输入/输出 - 不适用于运行函数。
以下是您的代码的版本:
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
processify
装饰器作为快捷方式:https://gist.github.com/2311116 - schlamar你可以使用标准的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上有一篇文章Python多进程编程,介绍了这两种技术。
fork
不可移植性的问题;通常我会给出非可移植性的答案,并提供它们是非可移植的信息,让提问者自行决定是否足够满意。由于我已经编辑了我的回答,如果您认为我已经做出了足够的改进,您应该可以取消您的负评;如果您没有这样做,也没有关系,我只是想检查一下我哪里做错了。 - Brian Campbellimport 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)
功能立即将线程置于后台。concurrent.futures.ProcessPoolExecutor
,它不仅传播返回值,还会传播任何异常。import concurrent.futures
# must be a global function
def my_function(x):
if x < 0:
raise ValueError
return x + 100
with concurrent.futures.ProcessPoolExecutor() as executor:
f = executor.submit(my_function, 1)
ret = f.result() # will rethrow any exceptions