2015-03-02 108 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