Creation and communication with daemon

Asked

Viewed 181 times

5

I have a Python application where I need to keep it online all the time.

The application has its own console, which is where I do the communication and step parameters.

I understood that I can create the Daemon to leave it online all the time, now the problem is that I still do not understand how to pass commands to the application being 'online'.

I have more familiarity with PHP, so I’m creating the daemon like this. I can already give the start, but still have no idea how to have a communication with it that is with the console open waiting commands.

I imagine that solving everything here will be difficult, but if you can give me some references and a path I study and I share the results.

1 answer

2

You need to look for an inter-process communication solution.

A popular way that works in a similar way across platforms and programming languages is to create a queue server (MQ). One of these is Zeromq and you can see some examples here.

Another way is to use the module multiprocessing from Python itself. Here’s a tested example, just to give you an idea where to start:

On your daemon, start the server waiting for client connections (console)

from multiprocessing.connection import Listener
import threading
import time

def processa_comando(comando):
    print 'Recebi o comando:', comando
    return {'status': 'OK', 'commando': comando}

def inicia_servidor():
    servidor = Listener(('localhost', 12345), authkey='senha')
    try:
        while True:
            # esperar conexao
            cnx = servidor.accept()
            # o codigo a seguir, em uma implementacao real,
            # poderia ser movido para uma thread nova (uma
            # para cada cliente conectado)
            print 'Client connected.'
            while True:
                # esperar comandos do cliente
                mensagem = cnx.recv()
                if mensagem['tipo'] == 'comando':
                    resposta = processa_comando(mensagem['comando'])
                    cnx.send(resposta)
                elif mensagem['tipo'] == 'exit':
                    print 'Client left.'
                    cnx.close()
                    break
    except Exception as err:
        print 'Erro', err
    finally:
        servidor.close()

# o servidor executa em uma thread separada para nao
# bloquear o programa principal
t = threading.Thread(target=inicia_servidor)
t.start()

# simulacao para mostrar que o servidor continua a
# trabalhar enquanto aguarda comandos
while True:
    print 'Servidor trabalhando...'
    time.sleep(5)

On your client (console) connect to the daemon

from multiprocessing.connection import Client

def aguarda_proximo_commando():
    commando = raw_input()
    return commando

cliente = Client(('localhost', 12345), authkey='senha')
try:
    while True:
        # fica em loop ate um CTRL+C
        print 'server>',
        texto = aguarda_proximo_commando()
        cliente.send({'tipo': 'comando', 'comando': texto})
        resposta = cliente.recv()
        print '  =>', resposta
except KeyboardInterrupt:
    cliente.send({'tipo': 'exit'})
except Exception as err:
    print 'Erro', err
finally:
    cliente.close()

Example of client execution:

~/teste $ python client.py 
server> ola
  => {'status': 'OK', 'commando': 'ola'}
server> tudo bem
  => {'status': 'OK', 'commando': 'tudo bem'}
server> ^C
~/teste $ python client.py 
server> ola de novo
  => {'status': 'OK', 'commando': 'ola de novo'}
server> ja vou
  => {'status': 'OK', 'commando': 'ja vou'}
server> ^C
~/teste $

Example result on the server:

~/teste $ python server.py 
Servidor trabalhando...
Servidor trabalhando...
Client connected.
Recebi o comando: ola
Servidor trabalhando...
Recebi o comando: tudo bem
Servidor trabalhando...
Client left.
Servidor trabalhando...
Client connected.
Servidor trabalhando...
Servidor trabalhando...
Recebi o comando: ola de novo
Servidor trabalhando...
Servidor trabalhando...
Recebi o comando: ja vou
Servidor trabalhando...
Client left.
Servidor trabalhando...
^CTraceback (most recent call last):
  File "server.py", line 46, in <module>
    time.sleep(5)
KeyboardInterrupt
^C^CTerminated: 15
~/teste $

Browser other questions tagged

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