有幾種方法從一個腳本/應用程序發送消息到另一個:
爲你的應用程序的有效方法是使用命名管道。使用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模式。
坦克很多!我將嘗試「命名管道」的方式... – EffegiWeb 2015-03-03 11:26:46
我不明白在檢查文件的情況下使用'select.select()'函數。 你能幫我一個例子嗎? 我需要等待無限循環中的消息。 – EffegiWeb 2015-03-03 16:21:19
我無法使select.select正常工作(我只在C程序中使用它),所以我將我的建議更改爲non-bloking模式並添加了一個示例。 – Patxitron 2015-03-04 09:33:43