Python service

Windows service [pywin32]

You can run a Python program with bat, but it's user-friendly if you can turn the running program into a service because you won't know what's running.

So, I will summarize how to register as a system

Setting method

  1. You have to pass the path to the system environment variables Control Panel \ System and Security \ System Advanced system settings → Environment variables

Check if the Path of the system environment variable has the following

--Note that it is not a user's environment variable --Python36 depends on the version you are using

C:\Users\〇〇〇〇\AppData\Local\Programs\Python\Python36\
C:\Users\〇〇〇〇\AppData\Local\Programs\Python\Python36\Scripts\

Also added the following

C:\Users\〇〇〇〇\AppData\Local\Programs\Python\Python36\Lib\site-packages\pywin32_system32
C:\Users\〇〇〇〇\AppData\Local\Programs\Python\Python36\Lib\site-packages\win32
  1. Execute from the command prompt with administrator privileges Note: How to run from administrator Search cmd → Command Prompt App → Right click and execute from administrator
pip install pywin32
  1. Service registration (automatic delay start) After moving to the directory containing the Python file to be systematized, open a command prompt with administrator privileges and execute the following command.
$ python test.py --startup delayed install
  1. Service execution Open a command prompt with administrator privileges and execute the following command.
$ python test.py start
  1. Service outage Open a command prompt with administrator privileges and execute the following command.
$ python test.py stop
  1. Delete service Open a command prompt with administrator privileges and execute the following command.
$ python test.py remove

Sample code 1

# -*- coding:utf-8 -*-

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket

import time
import threading
import logging
import random

logging.basicConfig(
    filename = 'c:\\work\\test-service.log',
    level = logging.DEBUG, 
    format="%(asctime)s:LINE[%(lineno)s] %(levelname)s %(message)s"
)

INTERVAL = 10

class MySvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "test-service"
    _svc_display_name_ = "test service"

    #Class initialization
    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.stop_event = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)
        self.stop_requested = False

    #Service outage
    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stop_event)
        logging.info('Request to Stop Service...')
        self.stop_requested = True

    #Start of the service
    def SvcDoRun(self):
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STARTED,
            (self._svc_name_,'')
        )
        
        #Main loop function call
        self.main_loop()
        
    #Main processing function
    def main_task(self):
        logging.debug('mainTask Start...55sec sleep')
        # time.sleep(55)
        logging.debug('Do Something...after 55sec')
    
    #Main loop function
    def main_loop(self):
        logging.info('Start of the service')
        exec_time = time.time()
        
        #Loop processing
        while True:
            #Confirmation of end request
            if self.stop_requested:
                logging.info('Stop service')
                break
                
            try: 
                #When the execution date and time is exceeded
                if exec_time <= time.time():
                    
                    #Main processing call
                    self.main_task()
                    
                    #Set the next execution time
                    exec_time = exec_time + INTERVAL
                    
            except Exception as e:
                logging.error("Error occured.")
                
            # 0.1 second sleep
            time.sleep(0.1)

        logging.info("Service outage")
        return

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(MySvc)

Sample code 2

.py:servicetest.py


import os
import win32service 
import win32serviceutil 
import win32event 
import datetime 
 
class SmallestPythonService(win32serviceutil.ServiceFramework): 
    #Service name
    _svc_name_ = "TESTServise" 
    #Display name(Show this on the service screen) 
    _svc_display_name_ = "TEST Service" 
    #Service description
    _svc_description_='Save data in the equipment operation table at regular intervals' 
    #Timeout time to wait for signal(This time 10 seconds= 10,000 ms) 
    _timeout_Milliseconds = 10000 
 
    def __init__(self, args): 
        win32serviceutil.ServiceFramework.__init__(self, args) 
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) 
 
    def SvcStop(self): 
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 
        win32event.SetEvent(self.hWaitStop) 
 
    def SvcDoRun(self): 
        print('Start of the service') 
        while 1: 
            #Wait 10 seconds for event signaling
            ret = win32event.WaitForSingleObject( 
                    self.hWaitStop, 
                    self._timeout_Milliseconds 
                    ) 
                #Service outage(Events are signaled)If so, stop processing
            if ret == win32event.WAIT_OBJECT_0: 
                break 
 
            self.main_loop() 
 
    #Actual service processing
    def main_loop(self): 
 
        # print('Start of the service') 
        #↓ ↓ Deleted for test test in the execution directory.Test OK once txt is created
        FILEADDR = os.path.dirname(os.path.abspath(__file__)) + '/test.txt'
        with open(FILEADDR, "a") as f:
            f.write("[Test] %s \n" % (datetime.datetime.now())) 
 
if __name__=='__main__': 
    win32serviceutil.HandleCommandLine(SmallestPythonService) 

Recommended Posts

Python service
Python
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
[Python] Sort
Note: Python
Python basics ③
python log
Python basics
[Scraping] Python scraping
Python update (2.6-> 2.7)
python memo
Python memorandum
Python # sort
ufo-> python
Python nslookup
python learning
Hannari Python 2020
[Rpmbuild] Python 3.7.3.
Prorate Python (1)
python memorandum
Download python
python memorandum