No Braves Studio
No Braves Studio

Reputation: 171

Python 3 Subprocess.stdin.write does not work | omxplayer class

For one of my projects, I need a way to create a custom Media Player class. to fo that I create a simple class that calls omxplayer with the given url and writes to the stdin letters like 'p' to pause, 'q' to quit... and so on Here is my code

import subprocess
import time

class MediaPlayer():
        def __init__(self):
                self.url = None
                self.process = None
        def play(self, url):
                self.url = url
                self.process = subprocess.Popen(['omxplayer', '-o', 'local', self.url], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
        def stop(self):
                self.process.stdin.write('q'.encode())
        def toogle_pause(self):
                self.process.stdin.write(b'p')

url = "/home/pi/Desktop/IOS MIRROR/films/Game.of.Thrones.S01E02.HDTV.VF.avi"

print('start')
media_player = MediaPlayer()
media_player.play(url)
time.sleep(15)
print('pause')
media_player.toogle_pause()
time.sleep(2)
print('resume')
media_player.toogle_pause()
time.sleep(10)
print('stop')
media_player.stop()

This works perfectly fine on python2.7, when I execute the command

python omx.py

but as soon as i execute the command

python3 omx.py

None of my write lines works, The video plays but it doesn't pause and stop. there is no error printed so I am really stucked. For informations, I am on a Raspberry Pi 3 powered by Raspbian. I need it to work on python3 because my Mirror project is using Python3

enter image description here

Thanks everyone for your answers! Best regards, Julien

Upvotes: 1

Views: 1661

Answers (1)

user484852
user484852

Reputation: 1

Resurrecting this because I just came across this and I'm not convinced the comment from jasonharper gives the full answer.

The reason is that the default for bufSize in Popen has changed from 0 (unbuffered) in python2 to 1 (line-buffered) in python3. Calling stdin.flush() after each write is one solution, but probably nicer is just to set this explicitly when creating the Popen by setting bufSize=0.

That should then result in the script working consistently in both python2 and 3.

Upvotes: 0

Related Questions