首页 文章

将消息发送到Python脚本

提问于
浏览
6

我正在尝试编写一个用于关闭的小python程序或重新启动我的Raspberry PI,由连接到GPIO的按钮驱动 . 该程序可以通过两个LED显示树莓PI(引导,运行,暂停,重新启动)的当前状态 . python程序作为守护进程执行,由init.d bash脚本(使用/etc/init.d/skeleton编写)启动 .

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

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

有人可以帮帮我吗?

谢谢 .

2 回答

  • 8

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

    对于您的应用程序,一个有效的方法是使用命名管道 . 使用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

    EDIT: 我无法使select.select正常工作(我只在C程序中使用它)所以我将我的推荐更改为非bloking模式 .

  • 1

    这个版本不是更方便吗?在 while true: 循环中使用 with costruct?这样,即使管道文件管理出错,循环内的所有其他代码也是可执行的 . 最终我可以使用 try: costuct来捕获错误 .

    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)
    

相关问题