如何以一般方式使由Python函数运行的可执行文件的终端输出静音?

如何以一般方式使由Python函数运行的可执行文件的终端输出静音?,第1张

如何以一般方式使由Python函数运行的可执行文件的终端输出静音

您可以从PyAudio切换到sounddevice模块,该模块已经负责使终端输出静音(请参阅#12)。这是在此完成的 *** 作(使用CFFI):

from cffi import FFIimport osffi = FFI()ffi.cdef("""FILE* fopen(const char* path, const char* mode);int fclose(FILE* fp);FILE* stderr;  FILE* __stderrp;  """)try:    stdio = ffi.dlopen(None)    devnull = stdio.fopen(os.devnull.enpre(), b'w')except OSError:    returntry:    stdio.stderr = devnullexcept KeyError:    try:        stdio.__stderrp = devnull    except KeyError:        stdio.fclose(devnull)

如果您想要一个纯Python解决方案,可以尝试以下上下文管理器:

import contextlibimport osimport [email protected] ignore_stderr():    devnull = os.open(os.devnull, os.O_WRONLY)    old_stderr = os.dup(2)    sys.stderr.flush()    os.dup2(devnull, 2)    os.close(devnull)    try:        yield    finally:        os.dup2(old_stderr, 2)        os.close(old_stderr)

这是关于该主题的非常有用的博客文章:http : //eli.thegreenplace.net/2015/redirecting-all-
kinds-of-stdout-in-python/


更新:

上面的上下文管理器使标准错误输出(

stderr
)静音,该错误用于原始问题中提到的来自PortAudio的烦人消息。如要删除标准输出(
stdout
),就像在更新的问题中一样,您必须将替换
sys.stderr
sys.stdout
,并将文件描述符
2
替换为数字
1

@contextlib.contextmanagerdef ignore_stdout():    devnull = os.open(os.devnull, os.O_WRONLY)    old_stdout = os.dup(1)    sys.stdout.flush()    os.dup2(devnull, 1)    os.close(devnull)    try:        yield    finally:        os.dup2(old_stdout, 1)        os.close(old_stdout)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5639591.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存