栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何以一般方式使由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 sys@contextlib.contextmanagerdef 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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633720.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号