且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

发送消息到Python脚本

更新时间:2022-11-26 13:59:15

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

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.