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?

Rinogg
  • 186
  • 8

1 Answers1

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)
Rinogg
  • 186
  • 8
  • 8
    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. – Dunes Sep 12 '18 at 18:06
  • 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. – tripleee Sep 12 '18 at 18:11
  • 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. – Rinogg Sep 13 '18 at 19:28