美文网首页
python3编写windwos服务

python3编写windwos服务

作者: 木木_bfe8 | 来源:发表于2018-06-04 13:56 被阅读0次

python版本3.6
需要安装pywin32Github
代码一部分抄网上别人的。

import win32serviceutil
import win32service
import win32event
import winerror
import servicemanager
import time
import sys


class PythonService(win32serviceutil.ServiceFramework):
    # 服务名
    _svc_name_ = "ALicense"
    # 服务显示名称
    _svc_display_name_ = "ALicense Is Exist "
    # 服务描述
    _svc_description_ = "ALicense  Is Exist License windows"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.run = True

    
    def SvcDoRun(self):
        '''服务启动后执行'''
        while self.run:
            self._Log('start')
            time.sleep(7)
                
    def SvcStop(self):
        '''服务停止时执行'''
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.run = False
        self._Log('stop')

    def _Log(self,str):
        with open('F:/helloServices.txt','a') as f:
            f.writelines('hello world'+str+'\n')

if __name__=='__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(PythonService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(PythonService)

服务安装
python PythonService.py install
让服务自动启动
python PythonService.py --startup auto install
启动服务
python PythonService.py start
重启服务
python PythonService.py restart
停止服务
python PythonService.py stop
删除/卸载服务
python PythonService.py remove

遇到问题

1、我是在vscode上编辑的。通过控制台执行main报pywintypes.error: (1063, 'StartServiceCtrlDispatcher', '服务进程无法连接到服务控制器上。')

原因由于windows service程序,不允许调试,所以如果你硬要调试,这个函数就回返回1063错误。那么怎么解决呢?很简单,你不能直接用vs进行调试。你只能通过打日志的方式,去看程序运行的问题。而必须要强调的是,你首先要注册,然后必须用sc命令或者windows服务器管理器去启动程序。手动启动或者vs调试都将失败。

2执行安装 报 Installing service ALicense Error installing service: 拒绝访问。 (5)

解决办法权限不够,以管理员身份运行vscode提升权限。安装运行一切正常

3我的python开发环境用的是虚拟环境,通过Anaconda Navigator构建的。发现注册服务后无法启动。

image.png

系统日志


image.png

执行安装运行环境不使用虚拟环境就可以正常运行。也可使用打包工具打包成exe安装。

相关文章

网友评论

      本文标题:python3编写windwos服务

      本文链接:https://www.haomeiwen.com/subject/pjoesftx.html