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
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
cmd
→ Command Prompt App → Right click and execute from administratorpip install pywin32
$ python test.py --startup delayed install
$ python test.py start
$ python test.py stop
$ python test.py remove
# -*- 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)
.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