2

pynotifyをインポートすると、常に厄介なGTKが表示されます-警告:

** (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'

問題は、それらを抑制する方法がわからないことです、私は試しました:

>>> 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'

動作しません、私が試した別のこと:

with warnings.catch_warnings():
    warnings.simplefilter('error')
    import pynotify

これも役に立ちません。

GTKメッセージが別のに届くようstderrです。それらを抑制する方法はありますか?

4

1 に答える 1

4

これらのメッセージを抑制するには、ファイル記述子を介してstderrをリダイレクトする必要があります。

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)

この関数の使用は次のように簡単です。

import sys

with suppress_output(sys.stderr):
    import pynotify
于 2012-07-20T15:02:23.173 に答える