首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >导入pynotify时出现GTK错误

导入pynotify时出现GTK错误
EN

Stack Overflow用户
提问于 2012-07-20 03:28:32
回答 1查看 1.6K关注 0票数 2

当导入pynotify时,我总是收到那些讨厌的GTK警告:

代码语言:javascript
复制
** (process:25512): WARNING **: Trying to register gtype 'GMountMountFlags' as enum when in fact it is of type 'GFlags'
** (process:25512): WARNING **: Trying to register gtype 'GDriveStartFlags' as enum when in fact it is of type 'GFlags'
** (process:25512): WARNING **: Trying to register gtype 'GSocketMsgFlags' as enum when in fact it is of type 'GFlags'

问题是,我不知道如何抑制它们,我试过了:

代码语言:javascript
复制
>>> import sys
>>> from io import BytesIO
>>> sys.stderr = BytesIO()
>>> sys.stdout = BytesIO()
>>> print 's'
>>> import pynotify

** (process:25512): WARNING **: Trying to register gtype 'GMountMountFlags' as enum when in fact it is of type 'GFlags'

** (process:25512): WARNING **: Trying to register gtype 'GDriveStartFlags' as enum when in fact it is of type 'GFlags'

** (process:25512): WARNING **: Trying to register gtype 'GSocketMsgFlags' as enum when in fact it is of type 'GFlags'

不起作用,我试过的另一件事是:

代码语言:javascript
复制
with warnings.catch_warnings():
    warnings.simplefilter('error')
    import pynotify

这也无济于事。

GTK消息似乎到达了不同的stderr。有什么办法抑制它们吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-20 23:02:23

要取消这些消息,您需要通过其文件描述符重定向stderr:

代码语言:javascript
复制
import os
from contextlib import contextmanager

@contextmanager
def suppress_output(fd):
    """
    Suppress output to the given ``fd``::

       with suppress_fd(sys.stderr):
           # in this block any output to standard error is suppressed

    ``fd`` is an integral file descriptor, or any object with a ``fileno()``
    method.
    """
    if hasattr(fd, 'fileno'):
        # we were given a file-like object with an underlying fd
        if hasattr(fd, 'flush'):
            # flush Python-side buffers before redirecting
            fd.flush()
        # get the fd to redirect
        fd = fd.fileno()

    # duplicate the file descriptor to restore it eventually
    oldfd = os.dup(fd)
    try:
        # open the trash can
        devnull = os.open(os.devnull, os.O_WRONLY)
        try:
            # point the file descriptor to the trash can
            os.dup2(devnull, fd)
        finally:
            # close the old trash can descriptor, we don't need it anymore
            # since the fd now points to the trash can
            os.close(devnull)
        # enter the callers block
        yield
        # restore the file descriptor
        os.dup2(oldfd, fd)
    finally:
        # close the duplicated copy of the original fd, we don't need it
        # anymore now that fd is restored
        os.close(oldfd)

此函数的用法非常简单,如下所示:

代码语言:javascript
复制
import sys

with suppress_output(sys.stderr):
    import pynotify
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11567930

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档