Subprocess.Popen stops ( or malfunctions) after a few seconds
Asked Answered
T

1

5

I am a complete beginner so apologies for any mistakes. This is my code in Python 3.5. It executes in Raspbian on a Raspberry Pi 3.

import subprocess

radio = subprocess.Popen(["mplayer", 'http://edge-bauerabsolute-02-gos1.sharp-stream.com/absolute90s.mp3?'], shell = False , stdout=subprocess.PIPE)

print ("Other code - no waiting for the subprocess to finish")

The radio plays for about 30 seconds and then stops. I want it to run in the background without the script waiting for the subprocess to end. Also, while in Linux, if I stop the script the radio comes back again as a running process of mplayer (so the python script must be stopping it somehow?)

It seems as if the subprocess continues but the music/sound stops. It does not seem to be internet connection related, also if I wait it it does not start again. I have tried doing radio.communicate() or radio.stdout.read() which funny enough lets my radio play continuously, but doesn't continue the script. I have no output from either, the script just holds.

Question: How do I allow the 'radio' process to continue in the background (with the music playing too) while the script does other things?

Tanney answered 12/9, 2018 at 13:59 Comment(0)
T
6

I have solved it myself luckily. The subprocess.PIPE apparently stops/interferes with the process so instead of stdout=subprocess.PIPE I have done DEVNULL like this:

DEVNULL = open(os.devnull, 'wb')
radiostream = subprocess.Popen(["mplayer", 'http://edge-bauerabsolute-02-gos1.sharp-stream.com/absolute90s.mp3?&'], shell = False, stdout=DEVNULL, stderr=DEVNULL)
Tanney answered 12/9, 2018 at 17:58 Comment(3)
What passing stdout=PIPE does is allows you to receive the output of the process. It goes into a buffer where you can read from. It's a limited size, so if don't read from the buffer relatively promptly then the buffer fills up and all future output will cause the process to hang until the buffer is read from (which frees up space). If you just want to hide the output then you can pass subprocess.DEVNULL which is more portable.Foundation
Alternatively, don't specify any destination for stdout and stderr; then the subprocess will share stdout/stderr with the parent process, i.e. your Python program. Who knows, maybe one day it prints a useful error message which it would be a shame to discard.Whiz
Dunes, tripleee thank you both very much. Dunes I assumed exactly what you just said having looked at the buffer size in the init.py of the subprocess module.Tanney

© 2022 - 2024 — McMap. All rights reserved.