是否可以使用python(标准python.org python)编写windows(10)服务而无需编译

时间:2017-10-25 12:18:12

标签: python windows-services

是否可以将Windows 10服务编写为python脚本而不涉及第三方软件,例如nssm或ActiveState python(不是说这两种方法都是错误的解决方案)。

  1. 脚本
  2. Python pip安装包
  3. 从命令行安装
  4. 可能的?

1 个答案:

答案 0 :(得分:1)

所以要使用this example我发现了一种最简单的方法来实现一个自给自足的python脚本而没有任何第三方编译器/服务:

安装win32模块包:

pip3 install pypiwin32

代码:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import sys


class TestService(win32serviceutil.ServiceFramework):
    _svc_name_ = 'TestService'
    _svc_display_name_ = 'TestService'

    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):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ''))
        self.main()

    def main(self):
        f = open('D:\\test.txt', 'a')
        rc = None
        while rc != win32event.WAIT_OBJECT_0:
            f.write('Test Service  \n')
            f.flush()
            # block for 24*60*60 seconds and wait for a stop event
            # it is used for a one-day loop
            rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)
        f.write('shut down \n')
        f.close()


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