1

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. Service snapshot

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

programmer
  • 124
  • 2
  • 10
  • Try starting your code with pythonw.exe as that doesn’t require a console window. – DisappointedByUnaccountableMod Sep 01 '21 at 06:36
  • The way to start a Windows service is either to use `net start` from the console, or to start it from the Services tab in Task Manager. Running it from a console, the way you have done, is only for debugging. – BoarGules Sep 01 '21 at 07:00
  • @BoarGules by using net start service has started successfully but my script is not working means it is not writing hello world in the file – programmer Sep 01 '21 at 07:12
  • 2
    Your code does not specify a location for the file. If Windows reports that the service is still running, then it is likely that the service *is* writing the file, but not to the location you expect. (1) Specify the full path to the file in the code: this is easiest for testing. But be sure it is a folder the service can write to. Or (2) make the location a command line parameter (`argparse`) and supply the folder name at start time in Services | Properties | General. For a real-world service, you would also need to add code that writes to the Windows Event Log to confirm what it is doing. – BoarGules Sep 01 '21 at 07:44
  • @BoarGules I have fulfilled your first suggestion specified full path but I can't understand your second suggestion ? – programmer Sep 06 '21 at 04:17
  • They were alternatives. It is inconvenient to have the location hard coded: that is suitable only for testing. A service can't use a relative path as in `open ('geek.txt' , 'a+')` because you then have no control over where the file is. The working directory will be different from what it was when you were testing interactively. The local system account is a different user. So you make the location a runtime option. If you don't understand what the `argparse` module is for then some time with the documentation would be a good idea. You can't write a command-line interface program without it. – BoarGules Sep 06 '21 at 06:19
  • @BoarGules Lets suppose I have an exe file of python which is writing into a file continuously whenever system restarts it will start again how can i achieve this? – programmer Sep 21 '21 at 04:37
  • @BoarGules I converted this .py file to a .exe file and install it using sc it has installed successfully but when i start this service it is giving me error. `[SC] StartService FAILED 1053: The service did not respond to the start or control request in a timely fashion.` – programmer Oct 12 '21 at 07:50
  • If you can't get the service to work, wrapping your program in an `.exe` just introduces an additional layer of complexity for no very obvious benefit. The only real use-case for that is when you want to deploy your program to systems that don't have Python installed. I don't know if the `pywin32` support for services even works when used that way. Even if it does, debugging is going to be very difficult. – BoarGules Oct 12 '21 at 08:01
  • @BoarGules I have successfully run my python script as a windows service and it is working properly but when I converted that working python script into an exe file and tried to start it as a service i got the error. – programmer Oct 12 '21 at 09:24
  • You don't say what you are using to create the `.exe` so it’s hard to suggest where to look for help. The `pyinstaller`documentation has a very helpful section called *When things go wrong*. The other tools all work pretty much the same way. I still say that `pywin32` was not written with that sort of thing in mind and may not work that way. I'm also still puzzled as to why you want an `.exe`. If that is what you want, why write your program in Python? It's an *interpreted language*. – BoarGules Oct 12 '21 at 09:39
  • @BoarGules what do you mean by interpreted language? means you want to say that if I want to run any exe file as a windows service it should not be written in python? – programmer Oct 12 '21 at 09:43
  • @BoarGules i used pyinstaller to create `.exe` – programmer Oct 12 '21 at 09:46
  • Try doing an online search for *interpreted language*. Python, like Java, is designed to be run by a virtual machine. You can't compile either language to machine code, only to bytecode, that needs the virtual machine to run it. What `pyinstaller` does is take the bytecode of your program, and of all its dependencies, and any DLLs they need, and bundles them together with a copy of `python.exe` and a despatcher into a huge self-extracting zipfile. The *only* benefit is ease of deployment, which makes it popular for games. Your program will take a long time to load, and won't run any faster. – BoarGules Oct 12 '21 at 10:00
  • @BoarGules but when i install my exe file as service using nssm it worked fine but when i tried to install and run it using command prompt it gave me error why? – programmer Oct 12 '21 at 10:23
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/238056/discussion-between-boargules-and-programmer). – BoarGules Oct 12 '21 at 10:29

1 Answers1

1

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.

Veeresh Devireddy
  • 1,057
  • 12
  • 24
programmer
  • 124
  • 2
  • 10