【问题标题】:Python 3.4: After popen.communicate() program is lostPython 3.4:popen.communicate() 程序丢失后
【发布时间】:2016-12-20 14:32:02
【问题描述】:

我将尝试在我的 RPi 上连接一个按钮来控制 mplayer,第一次按下按钮将启动播放器,然后每次按下按钮将播放播放列表中的另一个条目。 作为一个最小示例,我在 Linux Mint 18 和 Python3.4.3 上创建了以下脚本:

from time import sleep
from subprocess import Popen, PIPE, DEVNULL

cmd = ["mplayer", "-shuffle", "-playlist", "/path/to/playlist.m3u"]

if __name__ == '__main__':
    first = False
    p = None
    i = 0

    if first == False: # should simulate first button
        print("player starting")
        p = Popen(cmd, stdin=PIPE, stdout=DEVNULL)
        print("player started")
        first = True

    while 1:
        sleep(1)
        i += 1
        print(str(i)+ " " +str(first))

        if i == 5 and first == True: # should simulate each later button
            i = 0
            print("sending keystroke to mplayer")
            p.communicate(b"\n")[0] # mplayer plays next song, but the program is lost
            print("sended keystroke to mplayer - never printed")

输出是:

player starting
player started
1 True
2 True
3 True
4 True
5 True
sending keystroke to mplayer

现在我期待循环重启,但它不见了。 调试对我没有帮助。 你有什么想法如何解决问题以及如何返回循环?

谢谢。

【问题讨论】:

  • Popen.communicate() 尝试从 stdout 和 stderr 读取数据,直到 EOF 并等待进程终止。换句话说,它会一直阻塞,直到 mplayer 退出。

标签: python python-3.x subprocess popen


【解决方案1】:

我用 mplayer slave 解决了:

from time import sleep
from subprocess import Popen

pathtoControlFile = "/home/immi/mplayer-control"
cmd = ["mplayer", "-slave", "-input", "file="+pathtoControlFile, "-shuffle", "-playlist", "/media/immi/9A005723005705A3/Musik/playlist.m3u"]

if __name__ == '__main__':
    first = False
    i = 0

    if first == False:      # initial start
        print("player starting")
        p = Popen(cmd)
        print("player started")
        first = True

    while 1:
        sleep(1)
        i += 1
        print(str(i)+ " " +str(first))

        if i == 5 and first == True: # each later button
            i = 0
            print("sending keystroke to mplayer")
            with open(pathtoControlFile, "wb+", buffering=0) as fileInput:
                p = Popen(["echo", "pt_step next"], stdout=fileInput)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2016-07-28
    • 2018-03-12
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多