-1

Suppose such a minor program to play sound

#!/usr/bin/python3
from pydub import AudioSegment
from pydub.playback import play

bell_sound = AudioSegment.from_wav("/home/me/Music/audio/bell.wav")
play(bell_sound)

Upon running it, the terminal got multiple lines of propts

In [8]: run report_time_example.py  
Input #0, wav, from '/tmp/tmpsc7u87_e.wav':   0KB sq=    0B f=0/0
  Duration: 00:00:01.62, bitrate: 176 kb/s
    Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 11025 Hz, 1 channels, s16, 176 kb/s
   1.43 M-A:  0.000 fd=   0 aq=    0KB vq=    0KB sq=    0B f=0/0

Manually redirect the output to /dev/null

   !python report_time_example.py  &> /dev/null

How could get the job done inside the python code body.

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

1 Answers1

3

The contextlib module offers context managers to redirect stdout and stderr for precisely this purpose:

import contextlib
import os

with open(os.devnull, 'w') as null, \
     contextlib.redirect_stdout(null), contextlib.redirect_stderr(null):
    bell_sound = AudioSegment.from_wav("/home/me/Music/audio/bell.wav")
    play(bell_sound)

While in the with block, stdout and stderr are redirected; when the block is exited, the original handles are restored.

Note: redirect_stdout was introduced in 3.4, and redirect_stderr in 3.5; if you're still on 2.7 or the like, your only option is reassigning sys.stdout/sys.stderr manually, or using os.dup2 to replace the underlying file descriptors, but I'd recommend using modern Python first.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271