How can I kill omxplayer by Python Subprocess

2019-04-11 11:40发布

问题:

I'm playing with my Raspberry Pi GPIO. I connect 4 switch to GPIO.

I want to realize the function is

While hold switch 1. Stop the current movie, Play M01.mp4.

While hold switch 2. Stop the current movie, Play M02.mp4.

...

If no switch was holded, player M00.mp4 in loop.

I just learn python for 3days. I'm very appreciate that you can help me with detail code.

Popen.Terminate() or Kill() can kill scratch, why can not kill omxplayer?

#!/usr/bin/env python2.7
import subprocess,time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.IN)
GPIO.setup(24, GPIO.IN)
GPIO.setup(23, GPIO.IN)
GPIO.setup(22, GPIO.IN)
while True:
    if GPIO.input(25) == True:
        time.sleep(1)
        playProcess=subprocess.Popen(['scratch'],stdout=True)
        #Terminate() or Kill() can kill scratch.
        playProcess=subprocess.Popen(['omxplayer','/home/pi/pyStudy/DSCF4021.MP4'],stdout=True)
        #Terminate() or Kill() CAN NOT kill scratch.
        time.sleep(5)
        playProcess.terminate()

回答1:

The best thing you could do is to send the command though pipe see the below example

global playProcess
playProcess=subprocess.Popen(['omxplayer','/home/pi/pyStudy/DSCF4021.MP4'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, close_fds=True)
time.sleep(10)
playProcess.stdin.write('q')

some times this won't work then you have to do a flush

playProcess.stdin.flush()


回答2:

Thanks for your hints, etc about shutting down omxplayer with Python.

Using the following Code I got the listed Error

  streamVideo = subprocess.Popen(['omxplayer', '-o', 'local', 'Media/TestA.mp4'],   stdin=subprocess.PIPE, stdout=subprocess.PIPE,      stderr=subprocess.PIPE, close_fds=True)
  time.sleep(10)
  streamVideo.stdin.write('q')
  streamVideo.stdin.flush()

ERROR: streamVideo.stdin.write('q') IOError: [Errno 32] Broken pipe

How I Killed omxplayer in Python

streamVideo = Popen(['omxplayer', '-o', 'local', 'Media/TestA.mp4'])
time.sleep(10)  # Time for the clip to play
streamVideo = Popen(['omxplayer', '-i', 'Media/TestA.mp4'])  # Kills the Display