简体   繁体   中英

Python 3.4: After popen.communicate() program is lost

I'll try to connect a button on my RPi to control mplayer, first button press shall start the player, and each later button press shall play another entry in the playlist. As a minimal example I created following script on Linux Mint 18 and 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")

And the output is:

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

And now I'm expecting a restart of the loop, but it's missing. Debugging did not help me. Do you have any ideas how to solve the problem and how to return into the loop?

Thank you.

I solved it with 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM