Windows Service with Python

Asked

Viewed 1,019 times

-1

I’m new with python, and I’m wanting to create a windows service using the language, I saw that there are libraries for q be done until I found some example codes and tried to adapt, when use 'python name.py install' the service installs, but in windows service manager it does not start always presents

Windows could not start Servteste service on local computer.

Error 1053: Service did not respond to start or control request in a timely manner.

The purpose of the program is to download packages of updates inside the installation folder of a program already installed, you need to run as a service to have this automatic verification

anticipated thanks

import win32service

import win32serviceutil

import win32event

from model.Orientador import * #retorna strings com os diversos endereços necessarios por onde a aplicação precisa percorrer

from connections.Rede import Transferencia #uso de ftp

from model.Leitoras import * #Leitora de txt

from connections.Handler import Handler #conexao com BD

import time

from connections.teste import *

import os.path

class ServPython(win32serviceutil.ServiceFramework):

    _svc_name_ = "ServTeste"
    _svc_display_name_ = "Serv - Teste (Servicoteste)"
    _svc_description_ = ""


    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)



    def SvcDoRun(self):
        import servicemanager

        os.chdir('..')
        os.chdir('..')

        pasta_raiz = os.getcwd()
        pasta_inicio = pasta_raiz + 'pasta onde fica o arquivo .py'
        os.chdir(pasta_inicio) #função usada sempre que um objeto de outra pasta é usado

        localini = Orienta.local(4)
        os.chdir(pasta_inicio)

        bancolocal = LeitorTxt.leitor(2, localini)
        os.chdir(pasta_inicio)

        execucao = 0  #usado antes para determinar looping infinito
        rc = None

        while rc != win32event.WAIT_OBJECT_0:  # looping infinito

            t0 = time.sleep(1)  #####controle de tempo de verificação

            localatualizacao = Orienta.local(2)  ## endereço da pasta de atualizacao
            os.chdir(pasta_inicio)

            arquivotemporario = Transferencia.pacote(2, localatualizacao)  ##arquivo de controle para verificar se a versão é diferente ou não
            os.chdir(pasta_inicio)

            versaodisponivel = LeitorTxt.leitorFtp(1, localatualizacao)  # leitura do arquivo de controle
            versaodisponivel = int(versaodisponivel)

            arquivojabaixado = localatualizacao + '\\' + str(versaodisponivel) + '.rar'  ##endereço para verificar se o arquivo ja não existe

            if os.path.exists(arquivojabaixado):  ##verificação

                arquivoexiste = 'S'
            else:

                arquivoexiste = 'N'

            busca = Handler.query('select versaoatual from tab253', bancolocal)  ##consulta de versao no banco
            temporario = busca[0]
            versaolocal = temporario[0]
            os.chdir(pasta_inicio)

            if versaodisponivel > versaolocal and arquivoexiste == 'N':  ##inicio de download de pacotes se for diferente
                pacote = Transferencia.pacote(1, localatualizacao)
                os.chdir(localatualizacao)
                os.rename('atualizacao.rar', str(versaodisponivel) + '.rar')  ##renomeando arquivo
                os.chdir(pasta_inicio)

            execucao = 0  # garante looping infinito

            rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)



            def SvcStop(self):

                self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

                win32event.SetEvent(self.hWaitStop)


if __name__ == '__main__':

    win32serviceutil.HandleCommandLine(ServPython)

1 answer

0


I had this same problem recently, I tried using Pyinstall and other tools but without success. The only tool that served me satisfactorily was the PM2

You install her via npm in Node.js and the service starts running, using the command:

$ pm2 start app.js

With Python would:

$ pm2 start __init__.py

The service already starts running and can close the console that it continues running, as it is on console.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.