发送消息到Python脚本 [英] Send message to a Python Script

查看:190
本文介绍了发送消息到Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

现在我可以启动/停止/验证守护程序的状态,并且守护程序可以检查按钮连接的输入,以执行命令 shutdown -h now或 shutdown -r now。

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" .

为了显示树莓派PI的当前状态,我曾考虑过使用runlevels目录中的某些脚本将消息发送到守护程序,以更改led的状态。
但是我不知道如何在python程序中接收消息。

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.

有人可以帮助我吗?

谢谢。

推荐答案

有几种方法可以将消息从一个脚本/应用程序发送到另一个脚本/应用程序:

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

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

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)

然后您可以使用命令

echo您的消息>从bash脚本发送消息。 / tmp / mypipe

编辑:我无法获得select.select正常工作(我仅在C程序),所以我将建议更改为非中断模式。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆