Sep-25-2020, 11:20 AM
It will catch any exception that is raised when you try to execute the code inside
Also, is there any specific reason why you return the service as dict and not as Service object?
So
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
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs