向 Python 脚本发送消息

Send message to a Python Script

我正在尝试编写一个 python 小程序来关闭或重启我的 Raspberry PI,由连接到 GPIO 的按钮驱动。该程序可以通过两个 LED 显示 raspberry PI(引导、运行、停止、重启)的当前状态。 python 程序作为守护进程执行,由 init.d bash 脚本启动(使用 /etc/init.d/skeleton)。

现在我可以 start/stop/verify 守护程序的状态,守护程序可以检查按钮连接的输入,以执行命令 "shutdown -h now" 或 "shutdown -r now" 。

为了显示 raspberry PI 的当前状态,我想到了向守护进程发送消息,使用运行级别目录中的一些脚本来更改 LED 的状态。 但是我不知道如何在python程序中接收消息。

有人可以帮助我吗?

谢谢。

有几种方法可以将消息从一个 script/app 发送到另一个:

对于您的应用程序,一个有效的方法是使用命名管道。使用 os.mkfifo 创建它,在您的 python 应用程序中以只读方式打开它,然后等待它的消息。

如果您希望您的应用在等待时做其他事情,我建议您以非阻塞模式打开管道以查找数据可用性而不会阻塞您的脚本,如下例所示:

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)

然后您可以使用命令

从 bash 脚本发送消息

echo "your message" > /tmp/mypipe

编辑: 我无法让 select.select 正常工作(我只在 C 程序中使用它)所以我将我的建议更改为非阻塞模式。

这个版本是不是更方便? 在 while true: 循环中使用 with 构造? 这样,即使在管道文件管理出错的情况下,循环内的所有其他代码也是可执行的。最终我可以使用 try: costuct 用于捕获错误。

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)