Sitelet https://github.com/pythonthings/python-sounddevice/commit/2bc3de04015de357db0018dcdb87c1c0adfea8e5
Skip to content

Commit 2bc3de0

Browse files
committed
Redirect stderr only during initialization
1 parent 427971c commit 2bc3de0

1 file changed

Lines changed: 29 additions & 21 deletions

File tree

‎sounddevice.py‎

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2639,10 +2639,35 @@ def _get_device_id(id_or_query_string, kind, raise_on_error=False):
26392639

26402640

26412641
def _initialize():
2642-
"""Initialize PortAudio."""
2643-
global _initialized
2644-
_check(_lib.Pa_Initialize(), 'Error initializing PortAudio')
2645-
_initialized += 1
2642+
"""Initialize PortAudio.
2643+
2644+
This temporarily forwards messages from stderr to /dev/null
2645+
(where supported).
2646+
2647+
"""
2648+
old_stderr = None
2649+
try:
2650+
stdio = _ffi.dlopen(None)
2651+
except OSError:
2652+
pass
2653+
else:
2654+
for stderr_name in 'stderr', '__stderrp':
2655+
try:
2656+
old_stderr = getattr(stdio, stderr_name)
2657+
except _ffi.error:
2658+
continue
2659+
else:
2660+
devnull = stdio.fopen(_os.devnull.encode(), b'w')
2661+
setattr(stdio, stderr_name, devnull)
2662+
break
2663+
try:
2664+
_check(_lib.Pa_Initialize(), 'Error initializing PortAudio')
2665+
global _initialized
2666+
_initialized += 1
2667+
finally:
2668+
if old_stderr is not None:
2669+
setattr(stdio, stderr_name, old_stderr)
2670+
stdio.fclose(devnull)
26462671

26472672

26482673
def _terminate():
@@ -2667,23 +2692,6 @@ def _exit_handler():
26672692
_terminate()
26682693

26692694

2670-
def _ignore_stderr():
2671-
"""Try to forward PortAudio messages from stderr to /dev/null."""
2672-
try:
2673-
stdio = _ffi.dlopen(None)
2674-
devnull = stdio.fopen(_os.devnull.encode(), b'w')
2675-
except (OSError, AttributeError):
2676-
return
2677-
try:
2678-
stdio.stderr = devnull
2679-
except _ffi.error:
2680-
try:
2681-
stdio.__stderrp = devnull
2682-
except _ffi.error:
2683-
stdio.fclose(devnull)
2684-
2685-
2686-
_ignore_stderr()
26872695
_atexit.register(_exit_handler)
26882696
_initialize()
26892697

0 commit comments

Comments
 (0)