Python Forum
Code for reload windows services
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code for reload windows services
#1
Hi guys,

I'm an IT administrator the coding is not my strength.
I have created a script to reload automatically some program that run has services in windows.
But I'm not sure if my code is optimized, and if there is no something we can ameliorate.
Can you please have an overview of my code and tell me what is I can do anything better and if something sound wrong.
Also, if the indentation style is good.

Thanks in advance

import psutil
import win32serviceutil
import os
import datetime


def getService(Audiosrv):
    service = None
    try:
        service = psutil.win_service_get(Audiosrv)
        service = service.as_dict()
    except Exception as ex:
        print (str(ex))

    return service

service = getService('Audiosrv')

#print(service)

if service:
        print ("service trouvé")
else:
        print ("service not found")

if service and service['status'] == 'running':

        print ("service est en cours de fonctionnement")
else:

         print ("service est arreté")
         service = "Audiosrv"
         win32serviceutil.StartService(service)
         print("le service a été demarré")
         try:
             os.mkdir('C:\Ariane\Logs_script_vision')
         except:
             print("Dossier logs déja existant")
         finally:
             fichier = open("C:\Ariane\Logs_script_vision\Visionlogs.txt","a")
             fichier.write("\nLe fichier vision a été relancé par notre script le :")
             fichier.write(datetime.datetime.now().ctime())
             fichier.close()
Reply
#2
import os
import datetime
import psutil
import win32serviceutil


def get_service(service_name):
    try:
        service = psutil.win_service_get(service_name)
        return service.as_dict()
    except Exception as ex: # all-catch exceptions are not good
        print(ex)


if __name__ == '__main__':
    LOOKUP_SERVICE = 'Audiosrv'
    service = get_service(LOOKUP_SERVICE)

    if service:
        print("service trouvé.")
        if service.get('status') == 'runnig':
            print("service est en cours de fonctionnement")
        else:
            print("service est arreté")
            win32serviceutil.StartService(LOOKUP_SERVICE)
            print("le service a été demarré")
            try:
                os.mkdir(r'C:\Ariane\Logs_script_vision') # on windows back-slash in path may create problems. use raw string or forward slash
            except FileExistsError: # catch specifi error consistent with the msg you print
                print("Dossier logs déja existant")
            finally:
                with open(r"C:\Ariane\Logs_script_vision\Visionlogs.txt", "a") as fichier:
                    fichier.write(f"Le fichier vision a été relancé par notre script le :{datetime.datetime.now().ctime()}\n")
    else:
        print("service not found")
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thank you very much, you did it so fast and now it look so fine.

So helpfull specialy because I'm not so good in coding.
Reply
#4
Can you please explain me this please how does it work ?


except Exception as ex: # all-catch exceptions are not good
print(ex)


Does it display any execption ? it mean any error code that came out during the running of this méthode ?


Thank you very much
Reply
#5
It will catch any exception that is raised when you try to execute the code inside try block. In this case
        service = psutil.win_service_get(service_name)
        return service.as_dict()
In my opinion you should catch only psutil.NoSuchProcess error, raised when no service with that name exists. I really don't think it's possible to get any other error from that code, but even if there is some other error, it's better to get the full traceback in order to debug it easier.

Also, is there any specific reason why you return the service as dict and not as Service object?

So
import os
import datetime
import psutil
import win32serviceutil
 
 
def get_service(service_name):
    try:
        return psutil.win_service_get(service_name)
    except psutil.NoSuchProcess:
        return None
 
 
if __name__ == '__main__':
    LOOKUP_SERVICE = 'Audiosrv'
    service = get_service(LOOKUP_SERVICE)
 
    if service:
        print("service trouvé.")
        if service.status() == 'runnig':
            print("service est en cours de fonctionnement")
        else:
            print("service est arreté")
            win32serviceutil.StartService(LOOKUP_SERVICE)
            print("le service a été demarré")
            try:
                os.mkdir(r'C:\Ariane\Logs_script_vision') # on windows back-slash in path may create problems. use raw string or forward slash
            except FileExistsError: # catch specifi error consistent with the msg you print
                print("Dossier logs déja existant")
            finally:
                with open(r"C:\Ariane\Logs_script_vision\Visionlogs.txt", "a") as fichier:
                    fichier.write(f"Le fichier vision a été relancé par notre script le :{datetime.datetime.now().ctime()}\n")
    else:
        print("service not found")
now, because your function is only wrapper around psutil function, you can possibly shorten the code further

import os
import datetime
import psutil
import win32serviceutil
  
  
LOOKUP_SERVICE = 'Audiosrv'

try:
    service = psutil.win_service_get(LOOKUP_SERVICE)
except psutil.NoSuchProcess:
    print("service not found")
else:
    print("service trouvé.")
    if service.status() == 'runnig':
        print("service est en cours de fonctionnement")
    else:
        print("service est arreté")
        win32serviceutil.StartService(LOOKUP_SERVICE)
        print("le service a été demarré")
        try:
            os.mkdir(r'C:\Ariane\Logs_script_vision') # on windows back-slash in path may create problems. use raw string or forward slash
        except FileExistsError: # catch specifi error consistent with the msg you print
            print("Dossier logs déja existant")
        finally:
            with open(r"C:\Ariane\Logs_script_vision\Visionlogs.txt", "a") as fichier:
                fichier.write(f"Le fichier vision a été relancé par notre script le :{datetime.datetime.now().ctime()}\n")
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020