有几种方法从一个脚本/应用程序发送消息到另一个:
为你的应用程序的有效方法是使用命名管道。使用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