我在Mac OS X和Ubuntu 14.04上将此代码作为CherryPy Web Service运行。通过在python3上使用multiprocessing
,我想以异步的方式在Process Pool
内启动静态方法worker()
。Multiprocessing apply_async()在Ubuntu上不起作用
相同的代码在Mac OS X上完美运行,在Ubuntu 14.04 worker()
中无法运行。即通过调试代码POST
方法中,我能看到每一行执行 - 从
reqid = str(uuid.uuid4())
到
return handle_error(202, "Request ID: " + reqid)
在Ubuntu 14.04启动相同的代码,它不运行worker()
方法,甚至不是方法顶部的print()
(将被记录)。
下面是相关的代码(我只是省略了handle_error()
法):
import cherrypy
import json
from lib import get_parameters, handle_error
from multiprocessing import Pool
import os
from pymatbridge import Matlab
import requests
import shutil
import uuid
from xml.etree import ElementTree
class Schedule(object):
exposed = True
def __init__(self, mlab_path, pool):
self.mlab_path = mlab_path
self.pool = pool
def POST(self, *paths, **params):
if validate(cherrypy.request.headers):
try:
reqid = str(uuid.uuid4())
path = os.path.join("results", reqid)
os.makedirs(path)
wargs = [(self.mlab_path, reqid)]
self.pool.apply_async(Schedule.worker, wargs)
return handle_error(202, "Request ID: " + reqid)
except:
return handle_error(500, "Internal Server Error")
else:
return handle_error(401, "Unauthorized")
#### this is not executed ####
@staticmethod
def worker(args):
mlab_path, reqid = args
mlab = Matlab(executable=mlab_path)
mlab.start()
mlab.run_code("cd mlab")
mlab.run_code("sched")
a = mlab.get_variable("a")
mlab.stop()
return reqid
####
# to start the Web Service
if __name__ == "__main__":
# start Web Service with some configuration
global_conf = {
"global": {
"server.environment": "production",
"engine.autoreload.on": True,
"engine.autoreload.frequency": 5,
"server.socket_host": "0.0.0.0",
"log.screen": False,
"log.access_file": "site.log",
"log.error_file": "site.log",
"server.socket_port": 8084
}
}
cherrypy.config.update(global_conf)
conf = {
"/": {
"request.dispatch": cherrypy.dispatch.MethodDispatcher(),
"tools.encode.debug": True,
"request.show_tracebacks": False
}
}
pool = Pool(3)
cherrypy.tree.mount(Schedule('matlab', pool), "/sched", conf)
# activate signal handler
if hasattr(cherrypy.engine, "signal_handler"):
cherrypy.engine.signal_handler.subscribe()
# start serving pages
cherrypy.engine.start()
cherrypy.engine.block()
你可以尝试提供一个最小可重现的例子,这肯定会有所帮助。另外,“不运行”有点模棱两可......你有错误吗?你可以发布吗? – Peque
嗨@佩克,我没有错。我试图调试代码,但它似乎没有被执行 - 我只是从一些基本的'print()'语句开始,在输出显示的方法之外。我提供了一个最小可重现的例子。谢谢 – gc5