2015-03-02 109 views
5

我想写一个关闭的小python程序或重新启动我的树莓PI,驱动一个按钮连接到一个GPIO。该程序可以通过两个LED显示树莓PI(引导,运行,停止,重新启动)的当前状态。 python程序作为守护进程执行,由init.d bash脚本(使用/etc/init.d/skeleton写入)启动。发送消息到Python脚本

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

为了显示树莓派的当前状态,我曾想过使用runlevels directorys中的一些脚本向守护进程发送消息,以改变leds的状态。 但我不知道如何在python程序中接收消息。

有人可以帮助我吗?

谢谢。

回答

6

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

为你的应用程序的有效方法是使用命名管道。使用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程序中使用它)所以我改变了我的建议,以非bloking模式。

+0

坦克很多!我将尝试“命名管道”的方式... – EffegiWeb 2015-03-03 11:26:46

+0

我不明白在检查文件的情况下使用'select.select()'函数。 你能帮我一个例子吗? 我需要等待无限循环中的消息。 – EffegiWeb 2015-03-03 16:21:19

+0

我无法使select.select正常工作(我只在C程序中使用它),所以我将我的建议更改为non-bloking模式并添加了一个示例。 – Patxitron 2015-03-04 09:33:43

0

这个版本不是更方便吗? 与while true:循环内的with构造? 通过这种方式,即使管道文件管理中发生错误,循环内的所有其他代码也是可执行的。最终我可以使用try:成本 捕捉错误。

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

用os.open打开管道/文件多次fdopen是不安全的。当“with”语句超出作用域(print(“做其他事情”的句子))时,它会关闭文件描述符并且不能重新打开。此外,如果在另一个进程已连接的情况下关闭管道,该进程将收到SIGPIPE信号,并且很可能会终止其执行。你应该保持管道一直处于循环状态。 – Patxitron 2015-03-10 08:03:50

+0

@Patxitron:谢谢你的信息。 – EffegiWeb 2015-03-10 09:08:41