Send a message in Python Script

I am trying to write a small python program to shut down or restart my raspberry PI using a button connected to GPIO. The program can display the current state of raspberry PI (Booting, Running, Halting, Rebooting) using two LEDs. The python program runs as a daemon, launched by the init.d bash script (written using /etc/init.d/skeleton).

Now I can start / stop / check the status of the daemon, and the daemon can check the input where the button is connected, execute the command "shutdown -h now" or "shutdown -r now".

To show the current state of the raspberry PI, I thought about sending messages to the daemon using some script in the runlevel directories to change the status of the LEDs. But I do not know how to get a message in a python program.

Can anybody help me?

Thanks.

+5
source share
2 answers

There are several ways to send a message from one script / app to another:

For your application, the valid method is to use a named pipe. Create it using os.mkfifo , open it read-only in your python application and wait for messages on it.

If you want your application to do other things while waiting, I recommend that you open the channel in non-blocking mode to search for data availability without blocking your script, as shown in the following example:

import os, time pipe_path = "/tmp/mypipe" if not os.path.exists(pipe_path): os.mkfifo(pipe_path) # Open the fifo. We need to open in non-blocking mode or it will stalls until # someone opens it for writting pipe_fd = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK) with os.fdopen(pipe_fd) as pipe: while True: message = pipe.read() if message: print("Received: '%s'" % message) print("Doing other stuff") time.sleep(0.5) 

Then you can send messages from bash scripts with the command

echo "your message" > /tmp/mypipe

EDIT: I cannot select select.select to work correctly (I used it only in C programs), so I changed my recommendation to non-blocking mode.

+6
source

Is this version more convenient? With price with inside loop while true: :? Thus, all other codes within the loop are executed even in the event of an error in managing the channel files. In the end, I can use the try: value to detect the error.

 import os, time pipe_path = "/tmp/mypipe" if not os.path.exists(pipe_path): os.mkfifo(pipe_path) # Open the fifo. We need to open in non-blocking mode or it will stalls until # someone opens it for writting pipe_fd = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK) while True: with os.fdopen(pipe_fd) as pipe: message = pipe.read() if message: print("Received: '%s'" % message) print("Doing other stuff") time.sleep(0.5) 
0
source

Source: https://habr.com/ru/post/1214486/


All Articles