2016-08-13 5 views
0

Я попытаюсь подключить кнопку на моем RPi для управления mplayer, нажатие первой кнопки должно начинаться с проигрывателя, а каждое последующее нажатие кнопки должно воспроизводить другую запись в плейлисте , В минимальном примере я создал следующий скрипт на Linux Mint 18 и Python3.4.3:Python 3.4: После того, как программа popen.communicate() потеряна

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 

А теперь я ожидаю перезапуск цикла, но он отсутствует. Отладка не помогла мне. У вас есть идеи, как решить проблему и как вернуться в цикл?

спасибо.

+0

[ 'Popen.communicate()'] (https://docs.python.org/3.4/library/subprocess.html#subprocess.Popen.communicate) пытается прочитать данные из stdout и stderr до EOF и ждет завершения процесса. Другими словами, он блокируется до выхода mplayer. –

+0

Спасибо за подсказку. – immi1988

ответ

0

я решил его с MPlayer ведомым:

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)