使用py2exe创建Windows服务
问题描述:
我需要运行我的Python应用程序作为Windows服务。 我能做到这一点使用命令,python fservice.py install
python fservice.py start
现在,我要为使用py2exe我的应用程序创建EXE。 我已经按照从这个问题代码:link
setup.py使用py2exe创建Windows服务
from distutils.core import setup
import py2exe
import sys
if len(sys.argv) == 1:
sys.argv.append("py2exe")
sys.argv.append("-q")
class Target:
def __init__(self, **kw):
self.__dict__.update(kw)
# for the versioninfo resources
self.version = "0.0.1"
self.company_name = "flotomate"
self.copyright = "no copyright"
self.name = "flotomate"
myservice = Target(
# used for the versioninfo resource
description = "flotomate",
# what to build. For a service, the module name (not the
# filename) must be specified!
modules = ["fservice"]
)
setup(
service = [myservice]
)
fservice.py
import sys
import servicemanager
import win32serviceutil
import win32service
import win32event
import win32api
from pagent import app
class fservice(win32serviceutil.ServiceFramework):
_svc_name_ = 'flotomate' #here is now the name you would input as an arg for instart
_svc_display_name_ = 'flotomate' #arg for instart
_svc_description_ = 'flotomate'# arg from instart
def __init__(self, *args):
win32serviceutil.ServiceFramework.__init__(self, *args)
self.log('init')
self.stop_event = win32event.CreateEvent(None, 0, 0, None)
#logs into the system event log
def log(self, msg):
import servicemanager
servicemanager.LogInfoMsg(str(msg))
def sleep(self, minute):
win32api.Sleep((minute*1000), True)
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
try:
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.log('start')
self.start()
self.log('wait')
win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
self.log('done')
except Exception:
self.SvcStop()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.stop()
win32event.SetEvent(self.stop_event)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def start(self):
app.run(host='0.0.0.0',port=4999)
# to be overridden
def stop(self):
pass
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(fservice)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(fservice)
我使用的命令创建EXE,python setup.py py2exe
但是,当我尝试安装使用fservice.exe --install
的服务,我得到这个错误
Traceback (most recent call last):
File "boot_service.py", line 37, in <module>
AttributeError: 'module' object has no attribute 'Initialize
boot_service.py of py2exe
我使用Python 2.7.6和py2exe-0.6.9
答
我遇到同样的问题。我不知道你是否找到了解决方案
在我的情况下,原因是servicemanager未包含在编译的软件包中。似乎安装服务管理器库在python问题上有冲突。
为了解决这个问题,我卸载的ServiceManager如果是未使用或手动复制servicemanager.pyd到文件夹DIST和servicemager.pyc到DIST \ library.zip。如果在dist \ library.zip中有一个名为servicemanager的文件夹,请将其删除。
如果您已经有了更好的解决方案,请分享^^