简体   繁体   中英

Run Python script as a windows service

I know this question was asked so many times. I read all those questions but i didn't find out my problem's solution. My issue is that i have created below window service with help of this link. How do you run a Python script as a service in Windows? and I am running this service from command prompt. Here is my python script that i need to run as a service.

import traceback
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import getpass
import json
import pathlib
import urllib.request
import sys
from time import time , sleep
import uuid
from urllib.request import urlopen , Request
from urllib.parse import urlencode , quote_plus
import subprocess
import threading
import requests
from requests.sessions import session
import os
import cgitb
import logging

class PythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "PCSIGN"
    _svc_display_name_ = "PC SIGN"

    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 ):
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
        
    def main(  ):

        while True:
            file = open ( 'geek.txt' , 'a+' )
            file.write("hello world")
        file.close()

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(PythonService)
    PythonService.main()  

As you can see in the main function there is an infinite loop in which I am opening a file and writing hello world in it. I install & start my service from command prompt.

C:\wamp64\www\project\python\New folder>start /min python testing.py install
C:\wamp64\www\project\python\New folder>start /min python testing.py start

after that service installed and start working properly and another window appear.

It also makes an entry successfully in Services. 服务快照

But the issue here is when i close the above window of python console it stop writing hello world in the file don't know why kindly how can i make it persistent so that whenever system restarted my script start working automatically and start writing hello world in the file

Just a few days back I have successfully sorted out my issue I just made some changes to my code and it started working properly. I am only posting these answers for someone like me who got this issue in the future he can easily sort it out. This is the new code:

def WriteToFile():

    while True:
        file = open ( "C:\\file.txt" , "w" )
        now = datetime.now()
        now = now.strftime("%B %d, %y %H:%M:%S")
        file.write(now)

class Pythonservice(win32serviceutil.ServiceFramework):


    _svc_name_ = 'PC-Service'
    _svc_display_name_ = 'PC-Service'
    _svc_description_ = 'Freindly Service'

    @classmethod
    def parse_command_line(cls):

        win32serviceutil.HandleCommandLine(cls)

    def __init__(self, args):

        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):

        self.stop()
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):

        self.start()
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.main()

    def start(self):
        self.isrunning = True

    def stop(self):
       self.isrunning = False

    def main(self):
        WriteToFile()



if __name__ == '__main__':
    Pythonservice.parse_command_line()

After these changes, I opened up a command prompt as administrator and type this command to install my service.

C:\wamp64\www\project\python\New folder>python testing.py install

I got the success message. After successful installation, I started my service using this command

C:\wamp64\www\project\python\New folder>python testing.py start

and service started successfully I confirmed from service manager as well whether my service is running or not and it was running after restarting my pc service was still in running state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM