简体   繁体   中英

Python, mpg123 and subprocess not properly using stdin.write or communicate

ok, so my google-fu really kind of sucks and I was unable to find an answer, hopefully you folks can help me ^_^

ok, so what I thought would be a simple script is seemingly not communicating with its subprocess correctly, I'm running this line by line. I'm also using the mpg123 player, this is a Linux system (well, Raspberry Pi)

    from subprocess import Popen, PIPE, STDOUT
    p = Popen(["mpg123", "-C", "test.mp3"], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
    #wait a few seconds to enter this, "q" without a newline is how the controls for the player work to quit out if it were ran like "mpg123 -C test.mp3" on the command line
    p.communicate(input='q')[0]

I can run stdout.read() on it just fine, but using communicate for input just makes it hang and p.stdin.write('q') does seemingly nothing at all. This is python related though I have a feeling I'm also not looking in the right place in the mpg123 documentation. Please be kind as I'm exceptionally new to this ^_^

Check what arguments your mpg123 version understands. The following works on my machine:

#!/usr/bin/env python3
import time
from subprocess import Popen, PIPE, DEVNULL, STDOUT

p = Popen(["mpg123", "-K", "test.mp3"], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)

# wait a little
time.sleep(3)

# send command "Skip song", wait for the player to exit
p.communicate(b'n')[0]

It starts playing the file, waits ~3 seconds, and exits.

This is an awful solution, but it works in a pinch. I'm using this as a patch because for some reason, I cannot get Python libraries to play properly on my Raspberry Pi.

If you start mpg123 in remote mode ( mpg123 -R ), you can send commands to it far more easily:

proc = sp.Popen(["mpg123", "-R"], stdin=sp.PIPE)

Then, you can send commands to its stdin attribute.

Note:

  • The commands are different. To pause, it's "pause" , not " " for example. Run mpg123 -R in a console, then send it the help command to see a list of commands.
  • The commands need to be newline terminated.

From the docs:

-R, --remote

Activate generic control interface. mpg123 will then read and execute commands from stdin. Basic usage is ''load '' to play some file and the obvious ''pause'', ''command. ''jump '' will jump/seek to a given point (MPEG frame number). Issue ''help'' to get a full list of commands and syntax.

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