ホームページ  >  記事  >  バックエンド開発  >  PythonでWindowsシステムサービスを作成する例を詳しく解説

PythonでWindowsシステムサービスを作成する例を詳しく解説

高洛峰
高洛峰オリジナル
2017-03-28 09:46:051641ブラウズ

この記事では、主に Python について Windows システム サービスの作成に関連する情報を詳しく紹介します。興味のある方は参考にしてください

最近、インストールして使用する必要がある Python プログラムがあります。 a Windows システム サービスを実行しましたが、その過程でいくつかの落とし穴に遭遇したので、それらを整理しました。

Python サービス クラス

まず、Python プログラムはシステム サービスとして機能するために Windows システム

API を呼び出す必要があります。具体的な内容は次のとおりです:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time
import win32api
import win32event
import win32service
import win32serviceutil
import servicemanager
class MyService(win32serviceutil.ServiceFramework):
  _svc_name_ = "MyService"
  _svc_display_name_ = "My Service"
  _svc_description_ = "My Service"
  def init(self, args):
    self.log('init')
    win32serviceutil.ServiceFramework.init(self, args)
    self.stop_event = win32event.CreateEvent(None, 0, 0, None)
  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 BaseException as e:
      self.log('Exception : %s' % e)
      self.SvcStop()
  def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    self.log('stopping')
    self.stop()
    self.log('stopped')
    win32event.SetEvent(self.stop_event)
    self.ReportServiceStatus(win32service.SERVICE_STOPPED)
  def start(self):
    time.sleep(10000)
  def stop(self):
    pass
  def log(self, msg):
    servicemanager.LogInfoMsg(str(msg))
  def sleep(self, minute):
    win32api.Sleep((minute*1000), True)
if name == "main":
  if len(sys.argv) == 1:
    servicemanager.Initialize()
    servicemanager.PrepareToHostSingle(MyService)
    servicemanager.StartServiceCtrlDispatcher()
  else:
    win32serviceutil.HandleCommandLine(MyService)
pyinstaller パッケージ化

pyinstaller -F MyService.py
Test

# 安装服务
dist\MyService.exe install
# 启动服务
sc start MyService
# 停止服务
sc stop MyService
# 删除服务
sc delete MyService


以上がPythonでWindowsシステムサービスを作成する例を詳しく解説の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。