如何在python中重定向Gtk.Window()调用的stderr/stdout



我正在用python创建一个Gtk.Window()。因为我正在使用的主题,所以我会收到一些警告,例如:

Gtk-WARNING **: Theme parsing error: other-applications.css:35:21: 'px' is not a valid color name

但这没关系。我只想从命令行输出中隐藏此信息。

我尝试过但没有奏效的是:

# open /dev/null
devnull = open(os.devnull, 'w')
# redirect the stderr/out of the current process
sys.stdout = devnull
sys.stderr = devnull
# open the window
window = Gtk.Window()
print 'hello world'
# eventually restore previous stderr/out
...

问题是"hello world"没有打印(如预期的那样),但上述警告仍然出现。

有什么建议吗?

重定向

sys.stdoutsys.stderr只影响Python代码;在您的情况下,您看到的错误来自Gtk(在较低级别)。

您必须使用原始文件描述符进行重定向。看看这个:如何防止 C 共享库在 python 中的 stdout 上打印?

基本上这里有一些代码可以在C代码的最低级别重定向stdout,但不适用于 Python 代码(答案来自 Dietrich Epp):

def redirect_stdout():
    # Redirecting stdout
    sys.stdout.flush() # <--- important when redirecting to files
    newstdout = os.dup(1)
    devnull = os.open(os.devnull, os.O_WRONLY)
    os.dup2(devnull, 1)
    os.close(devnull)
    sys.stdout = os.fdopen(newstdout, 'w')

@Matyas。

该错误是由旧版本的 Gtk3 引起的,可能发生在 Debian Wheezy 或 Ubuntu 12.04 中。在 Gtk3.4 及更早版本中,不支持将px作为一个单元。

修复它的一种简单方法是创建两个 css 文件,一个带有 px,一个没有。在python中将样式文件加载为CssProvider时,请检查当前的gtk3版本,如下所示:

if Gtk.MINOR_VERSION < 6:
    # load other-applications-3.4.css
else:
    # load other-applications.css

我以前在我的项目中遇到过这种情况。

相关内容

最新更新