如何在python代码中执行ubuntu命令?

Din*_*esh 0 python command-line

我必须在 python 中执行这段代码

dconf write /org/compiz/profiles/unity/plugins/unityshell/alt-tab-prev "'Disabled'"
Run Code Online (Sandbox Code Playgroud)

尝试过:

os.system('dconf write /org/compiz/profiles/unity/plugins/unityshell/alt-tab-prev "Disabled" ')
Run Code Online (Sandbox Code Playgroud)

错误:

error: 0-1:unknown keyword

Usage:
  dconf write KEY VALUE 

Write a new value to a key

Arguments:
  KEY         A key path (starting, but not ending with '/')
  VALUE       The value to write (in GVariant format)
Run Code Online (Sandbox Code Playgroud)

请帮助我解决这个问题。谢谢 :-)

Jac*_*ijm 5

从 python 编辑 dconf/gsettings

你真的不应该再使用os.system()系统调用了,它已经被弃用并且完全过时了很长时间。

有不同的选项可以编辑dconf数据库。

使用子流程

说我有一个dconf路径/com/gexperts/Tilix/keybindings/app-shortcuts,我可以使用:

import subprocess

key = "/com/gexperts/Tilix/keybindings/app-shortcuts"

subprocess.Popen([
    "dconf", "write", key, "'enabled'"
])
Run Code Online (Sandbox Code Playgroud)

注意引用!


但是,在大多数情况下,您也可以使用 (better) gsettings。使用Gio.Settings如果该值也可以设置从gsettings


使用 Gio.Settings

from gi.repository import Gio

key = "com.gexperts.Tilix.Keybindings"

settings = Gio.Settings.new(key)
settings.set_string("app-shortcuts", "enabled")
Run Code Online (Sandbox Code Playgroud)

另见https://lazka.github.io/pgi-docs/#Gio-2.0/classes/Settings.html#Gio.Settingshttps://people.gnome.org/~gcampagna/docs/Gio-2.0/ Gio.Settings.html

关于 gsettings/dconf

现代 Ubuntu 版本的首选项大多dconf以二进制格式存储在数据库中。这些设置可以通过dconf(cli) 或dconf-editor(gui)直接编辑。Dconf 是低级的,通过dconf极快和轻量级直接编辑设置。

然而,一般来说,gsettings如果可能的话,通过cli 前端编辑数据库中的设置被认为是更好的做法dconf。原因是gsettings有一致性检查,使用更安全。

您可能会发现这是一个有趣的阅读gsettingshttps : //developer.gnome.org/gio/stable/GSettings.html

而这个dconfhttps : //developer.gnome.org/dconf/unstable/dconf-tool.html

笔记

  • 我使用了另一个路径/关键示例,因为我没有运行 Unity。