向 Python 脚本发送消息 [英] Send message to a Python Script
问题描述
我正在尝试编写一个用于关闭或重启我的 Raspberry PI 的 Python 小程序,由连接到 GPIO 的按钮驱动.该程序可以通过两个 LED 显示 raspberry PI 的当前状态(启动、运行、暂停、重新启动).python 程序作为守护进程执行,由 init.d bash 脚本(使用/etc/init.d/skeleton 编写)启动.
现在我可以启动/停止/验证守护进程的状态,守护进程可以检查按钮连接的输入,以执行命令shutdown -h now"或shutdown -r now".>
为了显示 raspberry PI 的当前状态,我想到了使用 runlevels 目录中的一些脚本向守护程序发送消息,以更改 LED 的状态.但是我不知道python程序中如何接收消息.
有人可以帮助我吗?
谢谢.
有几种方法可以将消息从一个脚本/应用程序发送到另一个:
对于您的应用程序,一个有效的方法是使用命名管道.使用 os.mkfifo 创建它,在你的 Python 应用中以只读方式打开它,然后然后等待消息.
如果您希望您的应用程序在等待时执行其他操作,我建议您以非阻塞模式打开管道以查找数据可用性而不阻塞您的脚本,如下例所示:
导入操作系统,时间pipe_path = "/tmp/mypipe"如果不是 os.path.exists(pipe_path):os.mkfifo(管道路径)# 打开先进先出.我们需要以非阻塞模式打开,否则它会停止直到# 有人打开它进行写作pipe_fd = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK)使用 os.fdopen(pipe_fd) 作为管道:而真:消息 = pipe.read()如果消息:print("收到:'%s'" % 消息)打印(做其他事情")时间.睡眠(0.5)
然后您可以使用命令从 bash 脚本发送消息
echo "你的消息" >/tmp/mypipe
我无法让 select.select 正常工作(我只在 C 程序中使用它)所以我将我的建议更改为非阻塞模式.
I'm trying to write a little python program for shutdown or Reboot my Raspberry PI, drived by a button connected to an GPIO. The program can show the current status of the raspberry PI (Booting,Running,Halting,Rebooting) via two leds. The python program is executed as daemon, started by a init.d bash script (written using the /etc/init.d/skeleton).
Now I can start/stop/verify the status of the daemon, and the daemon can check the input where the button is connected, to perform the command "shutdown -h now" or "shutdown -r now" .
For show the current status of the raspberry PI, I had thought of send messages to the daemon, using some script in the runlevels directorys, for change the status of the leds. But I don't know how receive message in the python program.
Someone can help me?
Thanks.
There are several methods to send a message from one script/app to another:
For you application a valid method is to use a named pipe. Create it using os.mkfifo, open it read-only in your python app and then wait for messages on it.
If you want your app to do another things while waiting, I reccomend you open the pipe in non-blocking mode to look for data availability without blocking your script as in 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 using the command
echo "your message" > /tmp/mypipe
EDIT: I can not get select.select working correctly (I used it only in C programs) so I changed my recommendation to a non-bloking mode.
这篇关于向 Python 脚本发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!