[英]How to install a Python Windows service using cx_Freeze?
我目前有一个 Python 文件,当使用 python file_name.py 运行时,它会安装一个 Windows 服务,该服务可在应用程序日志下的事件查看器中查看,并可使用 sc stop service_name 停止。 但是,当使用 cx_Freeze 转换为可执行文件时,可执行文件运行时没有错误,但服务不再安装。 如果我只运行可执行文件本身,如果我运行 service_name.exe --install service_name,或者如果我运行 sc create service_name binPath=service_path,就会发生这种情况
我的 setup.py 文件看起来像:
from cx_Freeze import setup, Executable
options = {
'build_exe': {
'packages': ['packagename'],
'includes': ['ServiceHandler', 'cx_Logging']}
}
setup(name='cx_FreezeSampleService',
version='0.1',
description='Sample cx_Freeze Windows serice',
executables=Executable('Config.py', base='Win32Service',
targetName='cx_FreezeSampleService.exe'),
options=options
)
我的 Config.py 看起来像:
NAME = 'cx_FreezeSampleService%s'
DISPLAY_NAME = 'cx_Freeze Sample Service - %s'
MODULE_NAME = 'ServiceHandler'
CLASS_NAME = 'Handler'
DESCRIPTION = 'Sample service description'
AUTO_START = True
SESSION_CHANGES = False
最后,我的 ServiceHandler.py 看起来像:
class Handler(object):
def Initialize(self, Config):
pass
def Run(self):
#code to run service
def Stop(self):
#code to stop service
此代码遵循此处 cx_Freeze 源代码中的示例( https://bitbucket.org/anthony_tuininga/cx_freeze/src/1282b6b6ee637738210113dd88c3c198d475340f/cx_Freeze/samples/service/?at几乎既不是示例,也不是默认示例)实际安装服务。
先感谢您!
这是一个老问题,但我设法在开发人员的帮助下将它作为一个简单的烧瓶应用程序的窗口服务工作。 [https://github.com/marcelotduarte/cx_Freeze/tree/master/cx_Freeze/samples/service]
您必须设置您想要性能的所有 Windows 服务操作。 这就是 ServiceHandler.py 作为模板的样子,您仍然需要适应以运行您的应用程序。
"""
Implements a simple service using cx_Freeze.
See below for more information on what methods must be implemented and how they
are called.
"""
import threading
import os
import sys
import cx_Logging
class Handler:
# no parameters are permitted; all configuration should be placed in the
# configuration file and handled in the Initialize() method
def __init__(self):
self.stopEvent = threading.Event()
self.stopRequestedEvent = threading.Event()
# called when the service is starting
def initialize(self, configFileName):
self.directory = os.path.dirname(sys.executable)
cx_Logging.StartLogging(os.path.join(self.directory, "teste.log"), cx_Logging.DEBUG)
#pass
# called when the service is starting immediately after Initialize()
# use this to perform the work of the service; don't forget to set or check
# for the stop event or the service GUI will not respond to requests to
# stop the service
def run(self):
cx_Logging.Debug("stdout=%r", sys.stdout)
sys.stdout = open(os.path.join(self.directory, "stdout.log"), "a")
sys.stderr = open(os.path.join(self.directory, "stderr.log"), "a")
self.stopRequestedEvent.wait()
self.stopEvent.set()
# called when the service is being stopped by the service manager GUI
def stop(self):
self.stopRequestedEvent.set()
self.stopEvent.wait()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.