Python 3可执行文件作为Windows服务 [英] Python 3 executable as windows service
问题描述
我正在尝试用python编写Windows服务,但棘手的部分是我想将其部署在没有python的计算机上。
我已经成功创建了一个服务,例如这,并且如果我从计算机上运行,它也可以工作。当我尝试将其转换为exe然后尝试安装时,问题开始了。
首先,我尝试使用cx_freeze服务示例,(见这里),setup.py如下所示:
I'm trying to write a windows Service in python, but the tricky part is i want to deploy it on a machine that doesn't have python. I've successfully created a service like this, and it works if i run from my machine. the problem starts when i try to convert it to an exe and then try to install it. first i tried to use cx_freeze service example, (seen here), the setup.py look like this :
from cx_Freeze import setup, Executable
options = {'build_exe': {'includes': ['ServiceHandler']}}
executables = [Executable('Config.py', base='Win32Service', targetName='gsr.exe')]
setup(name='GSR',
version='0.1',
description='GSR SERVICE',
executables=executables,
options=options
)
和config.py为:
and config.py is:
NAME = 'GSR_%s'
DISPLAY_NAME = 'GSR TEST - %s'
MODULE_NAME = 'ServiceHandler'
CLASS_NAME = 'Handler'
DESCRIPTION = 'Sample service description'
AUTO_START = True
SESSION_CHANGES = False
但是当我尝试构建它(python setup.py build)时,我得到了e rror:
cx_Freeze.freezer.ConfigError:没有名为Win32Service的库
but when i try to build it (python setup.py build) i get an error: "cx_Freeze.freezer.ConfigError: no base named Win32Service"
第二,我尝试使用常规的cx_freeze设置,我安装的exe安装了该服务很好,但是一旦我尝试启动它,我会收到一个错误:
错误1053:该服务没有及时响应启动或控制请求
Second, i tried using a regular cx_freeze setup, the exe i get installs the service fine but once i try to start it i get an error: "Error 1053: The service did not respond to the start or control request in a timely fashion"
setup.py-python 3.3 regualr exe,安装了该服务,但是在尝试启动时会发送错误:
setup.py - python 3.3 regualr exe, installs the service but when trying to start it sends an error:
from cx_Freeze import setup, Executable
packages = ['win32serviceutil','win32service','win32event','servicemanager','socket','win32timezone','cx_Logging','ServiceHandler']
build_exe_options = {"packages": packages}
executable = [Executable("ServiceHandler.py")]
setup( name = "GSR_test",
version = "1.0",
description = "GSR test service",
options = {"build_exe": build_exe_options},
executables = executable)
f最终,我设法使用py2exe在python 2.7中运行它,但是py2exe无法用于python 3.3,我的代码在3.3中。
finally, I managed to get it to work in python 2.7 using py2exe, but py2exe isn't available for python 3.3 and I my code is in 3.3
我猜是问题所在与cx_freeze一起使用时在setup.py im的配置中。
任何想法??
i guess the problem is in the configuration of the setup.py im using with cx_freeze. any ideas ??
我的ServiceHandler:
my ServiceHandler:
import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
from test import test
import threading
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "GSR_test"
_svc_display_name_ = "GSR test Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
self.app = test()
self.flag = threading.Event()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.flag.set()
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
t = threading.Thread(target=self.app.run)
t.start()
self.flag.wait()
raise SystemExit
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
Setup.py,python 2.7使用有效的py2exe :(摘自此处)
Setup.py , python 2.7 using py2exe that works: (taken from here)
from distutils.core import setup
import py2exe
setup( service = ["ServiceHandler"],
description = "SERVICE TEST",
modules = ["GSR_test"],
cmdline_style='pywin32', )
谢谢,
Amit
Thanks, Amit
推荐答案
tldr Python 3.5 Windows使用pyin构建服务档位:要点
tldr Python 3.5 Windows Service build with pyinstaller : gist
这里很简单带有python的Windows Service:
Here a simple Windows Service with python :
WindowsService.py
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil
class TestService(win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
rc = None
while rc != win32event.WAIT_OBJECT_0:
with open('C:\\TestService.log', 'a') as f:
f.write('test service running...\n')
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(TestService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(TestService)
使用pyinstaller创建exe( pip install pyinstaller
)和python 3.5:
Create an exe with pyinstaller (pip install pyinstaller
) and python 3.5 :
(env)$ python -V
Python 3.5.2
(env)$ pip freeze
PyInstaller==3.2
(env)$ pyinstaller -F --hidden-import=win32timezone WindowsService.py
安装并运行服务
(env) dist\WindowsService.exe install
Installing service TestService
Service installed
(env) dist\WindowsService.exe start
Starting service TestService
检查 C:\\TestService.log
文件。
停止并清理
(env) dist\WindowsService.exe stop
(env) dist\WindowsService.exe remove
这篇关于Python 3可执行文件作为Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!