Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to feed information to a Python daemon?

I have a Python daemon running on a Linux system. I would like to feed information such as "Bob", "Alice", etc. and have the daemon print "Hello Bob." and "Hello Alice" to a file.

This has to be asynchronous. The Python daemon has to wait for information and print it whenever it receives something.

What would be the best way to achieve this?

I was thinking about a named pipe or the Queue library but there could be better solutions.

like image 312
mimipc Avatar asked Mar 18 '15 16:03

mimipc


People also ask

How do I run a daemon process in python?

Daemon processes in Python To execute the process in the background, we need to set the daemonic flag to true. The daemon process will continue to run as long as the main process is executing and it will terminate after finishing its execution or when the main program would be killed.

What is a python daemon?

daemon-This property that is set on a python thread object makes a thread daemonic. A daemon thread does not block the main thread from exiting and continues to run in the background. In the below example, the print statements from the daemon thread will not printed to the console as the main thread exits.

How do I run a python script as a service Ubuntu?

Insert the username in your OS where <username> is written. The ExecStart flag takes in the command that you want to run. So basically the first argument is the python path (in my case it's python3) and the second argument is the path to the script that needs to be executed.


1 Answers

Here is how you can do it with a fifo:

# receiver.py

import os
import sys
import atexit

# Set up the FIFO
thefifo = 'comms.fifo'
os.mkfifo(thefifo)

# Make sure to clean up after ourselves
def cleanup():
    os.remove(thefifo)
atexit.register(cleanup)

# Go into reading loop
while True:
    with open(thefifo, 'r') as fifo:
        for line in fifo:
            print "Hello", line.strip()

You can use it like this from a shell session

$ python receiver.py &
$ echo "Alice" >> comms.fifo
Hello Alice
$ echo "Bob" >> comms.fifo
Hello Bob
like image 61
chthonicdaemon Avatar answered Sep 22 '22 21:09

chthonicdaemon