我正在尝试设置Windows服务,该服务将使用Pywin32,CherryPy和Python3.6运行Django项目。我已经使用Python3.5成功完成了此操作,但是升级导致sys.path好像没有virtualenv处于活动状态。
尝试运行服务时,出现服务错误,提示
“ Windows无法在本地启动Project CherryPy服务 电脑。有关更多信息,请查看系统事件日志。如果这 是非Microsoft服务,请与服务供应商联系,并参考 特定于服务的错误代码1。“
查看事件日志,我可以看到Django无法加载:
from django.core.wsgi import get_wsgi_application
ModuleNotFoundError: No module named 'django'
检查后,我发现除了“ ... \ lib \ site-packages \ win32”外,我的项目中的virtualenv路径均不在sys.path中。
那么,如何在不手动添加所需路径的情况下使服务在正确的virtualenv活动下运行?(以便它与将来的开发配合使用)?以下适用于Python3.5:
CherryPyService.py:
import cherrypy
import win32serviceutil
import win32service
import sys
import os
from my_project import wsgi
DEPLOY_DIRECTORY = "C:/home/code/my_project/"
ERROR_LOG = os.path.join(DEPLOY_DIRECTORY,"service_logs","cherry_py_err.log")
STD_ERR = os.path.join(DEPLOY_DIRECTORY,"service_logs","std_err.log")
STD_OUT = os.path.join(DEPLOY_DIRECTORY,"service_logs","std_out.log")
sys.stdout = open(STD_OUT,'a')
sys.stderr = open(STD_ERR,'a')
class ProjectService(win32serviceutil.ServiceFramework):
_svc_name_ = "ProjectCherryPyService"
_svc_display_name_ = "Project CherryPy Service"
def SvcDoRun(self):
sys.path.append(DEPLOY_DIRECTORY)
os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings'
os.chdir(DEPLOY_DIRECTORY)
cherrypy.tree.graft(wsgi.application)
cherrypy.config.update({
'global':{
'log.error_file':ERROR_LOG,
'log.screen': False,
'tools.log_tracebacks.on':True,
'engine.autoreload.on': False,
'engine.SIGHUP': None,
'engine.SIGTERM': None,
'server.socket_port': 8030,
}
})
cherrypy.engine.start()
cherrypy.engine.block()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
cherrypy.engine.exit()
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(ProjectService)
wsgi.py:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()