如何在尝试使用它之前确定是否存在GSettings模式?

9

如果存在已编译的GSettings架构,则通常可以轻松读取,但是如果不存在,则通常会抛出无法处理的错误。在Python文件或控制台中尝试以下操作:

from gi.repository import Gio
try:
    settings = Gio.Settings("com.example.doesnotexist")
except:
    print "Couldn't load those settings!"

我这里使用了最宽泛的except,但是抛出的错误就是这个。

(process:10248): GLib-GIO-ERROR **: 设置模式 'com.example.doesnotexist' 没有安装

我想要做的基本上就是查找 com.example.doesnotexist 模式是否存在。如果不存在,就告诉用户在使用我的应用程序之前运行我的安装脚本。欢迎提供任何其他建议。

2个回答

7
你可以使用 GSettingsSchemaSource。例如:
> from gi.repository import Gio
> source = Gio.SettingsSchemaSource.get_default()
> source.lookup("org.gnome.Epiphany", True)
<GSettingsSchema at 0xa462800>
> source.lookup("com.example.doesnotexist", True)

>

根据文档,如果模式不存在,则查找应返回 NULL ( None ),但在PyGObject中返回了NoneType。 无论如何,您可以使用它来检查模式是否存在。

太好了,非常感谢。我不知道你是怎么想出来的,但我自己做不到,所以很感激你抽出时间来做这件事。 - Mendhak

0

我知道这是针对Python的。但是这里有一个适用于使用C语言的解决方案:

gboolean g_settings_schema_exist (const char * id)
{ 
  gboolean ret = FALSE;
  GSettingsSchema * res = g_settings_schema_source_lookup (
                                 g_settings_schema_source_get_default(), 
                                 id, FALSE);                                 
  if (res != NULL)
  {
    ret = TRUE;
    g_object_unref (res);
  }
  
  return ret;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接