write DBUS Services (I)

Those days I had to make a D-Bus server and client in python and I thought to share with you guys some things about the D-Bus.

First of all, what is D-Bus? Well, D-Bus is a system that offers a communication channel for multiple programs.

Someone must also distinguish between: session and system bus.

The session bus is specific for each user, while the system bus is specially designed for the state of the whole system and can change this state (like adding a new storage device, the internet connection suffers some modification).

“Talk is cheap, show me the code”  Linus Torvalds

One example of a  session bus server is the following

#!/usr/bin/env python3

from gi.repository import GLib
import dbus
import dbus.service

from dbus.mainloop.glib import DBusGMainLoop

class Session_DBus(dbus.service.Object):
    def __init__(self):
        bus_name=dbus.service.BusName('org.me.test_session',bus=dbus.SessionBus())
        dbus.service.Object.__init__(self,bus_name,'/org/me/test_session')

    @dbus.service.method('org.me.test1')
    def session_bus_message1(sefl):
        return "Session Bus 1"

    @dbus.service.method('org.me.test2')
    def session_bus_message2(self):
        return "Session Bus 2"

    @dbus.service.method('org.me.test2')
    def session_bus_strings(self,string1,string2):
        return string1+" "+string2



DBusGMainLoop(set_as_default=True)
dbus_service=Session_DBus()

try:
    GLib.MainLoop().run()
except KeyboardInterrupt:
    print("\nThe MainLoop will close...")
    GLib.MainLoop().quit()

And the client (2 versions):

Version 1:

#!/usr/bin/env python3

import dbus
bus = dbus.SessionBus()
session = bus.get_object("org.me.test_session", "/org/me/test_session")

method_message1 = session.get_dbus_method('session_bus_message1', 'org.me.test1')
method_message2 = session.get_dbus_method('session_bus_message2', 'org.me.test2')
method_message3 = session.get_dbus_method('session_bus_strings', 'org.me.test2')

print(method_message1())
#interface1 = dbus.Interface(session, "org.me.test1")
#print(interface1.session_bus_message1())
print(method_message2())
print(method_message3("Hello", "World"))

Version 2:

#!/usr/bin/env python3

import dbus
bus = dbus.SessionBus()
session = bus.get_object("org.me.test_session", "/org/me/test_session")
interface1 = dbus.Interface(session, "org.me.test1")
interface2 = dbus.Interface(session, "org.me.test2")

print(interface1.session_bus_message1())
print(interface2.session_bus_message2())
print(interface2.session_bus_strings("hello", "world"))

For the client scripts to run, one must first run the script for the  server and after that to run the clients. Also if you want to have to have the  server initiated (to not manually run it) you could create a file with a .service extension  in /usr/share/dbus-1/service/; let’s say  my-test-session.service with the following content:

[D-BUS Service]
Name=org.me.test_session
Exec="/home/charles/my-test-session.py"

After this you can run only the  clients and the system would know where  server part is and how to handle it. Also, do not forget to make the server script executable.


we can verify this service using dbus tools:

$ dbus-send --session --type=method_call --print-reply --dest="org.me.test_session" /org/me/test_session org.freedesktop.DBus.Introspectable.Introspect
method return time=1491700435.911482 sender=:1.133 -> destination=:1.134 serial=3 reply_serial=2
   string "<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node name="/org/me/test_session">
  <interface name="org.freedesktop.DBus.Introspectable">
    <method name="Introspect">
      <arg direction="out" type="s" />
    </method>
  </interface>
  <interface name="org.me.test1">
    <method name="session_bus_message1">
    </method>
  </interface>
  <interface name="org.me.test2">
    <method name="session_bus_message2">
    </method>
    <method name="session_bus_strings">
      <arg direction="in"  type="v" name="string1" />
      <arg direction="in"  type="v" name="string2" />
    </method>
  </interface>
</node>
"

dbus-send --session --type=method_call --print-reply --dest="org.me.test_session" /org/me/test_session org.me.test2.session_bus_strings string:"hello" string:"world"
method return time=1491700611.464318 sender=:1.133 -> destination=:1.137 serial=4 reply_serial=2
   string "hello world"

https://georgemuraruc.wordpress.com/2015/07/16/d-bus-tutorial-for-python/


root@zhang:~# dpkg --list | grep -i python ii libpython3-stdlib:amd64 3.12.3-0ubuntu2 amd64 interactive high-level object-oriented language (default python3 version) ii libpython3.12-minimal:amd64 3.12.3-1ubuntu0.4 amd64 Minimal subset of the Python language (version 3.12) ii libpython3.12-stdlib:amd64 3.12.3-1ubuntu0.4 amd64 Interactive high-level object-oriented language (standard library, version 3.12) ii libpython3.12t64:amd64 3.12.3-1ubuntu0.4 amd64 Shared Python runtime library (version 3.12) ii python-apt-common 2.7.7ubuntu4 all Python interface to libapt-pkg (locales) ii python-babel-localedata 2.10.3-3build1 all tools for internationalizing Python applications - locale data files ii python3 3.12.3-0ubuntu2 amd64 interactive high-level object-oriented language (default python3 version) ii python3-apport 2.28.1-0ubuntu3.3 all Python 3 library for Apport crash report handling ii python3-apt 2.7.7ubuntu4 amd64 Python 3 interface to libapt-pkg ii python3-aptdaemon 1.1.1+bzr982-0ubuntu44 all Python 3 module for the server and client of aptdaemon ii python3-aptdaemon.gtk3widgets 1.1.1+bzr982-0ubuntu44 all Python 3 GTK+ 3 widgets to run an aptdaemon client ii python3-attr 23.2.0-2 all Attributes without boilerplate (Python 3) ii python3-babel 2.10.3-3build1 all tools for internationalizing Python applications - Python 3.x ii python3-blinker 1.7.0-1 all Fast, simple object-to-object and broadcast signaling (Python3) ii python3-bpfcc 0.29.1+ds-1ubuntu7 all Python 3 wrappers for BPF Compiler Collection (BCC) ii python3-brlapi:amd64 6.6-4ubuntu5 amd64 Braille display access via BRLTTY - Python3 bindings ii python3-cairo 1.25.1-2build2 amd64 Python3 bindings for the Cairo vector graphics library ii python3-certifi 2023.11.17-1 all root certificates for validating SSL certs and verifying TLS hosts (python3) ii python3-cffi-backend:amd64 1.16.0-2build1 amd64 Foreign Function Interface for Python 3 calling C code - runtime ii python3-chardet 5.2.0+dfsg-1 all Universal Character Encoding Detector (Python3) ii python3-click 8.1.6-2 all Wrapper around optparse for command line utilities - Python 3.x ii python3-colorama 0.4.6-4 all Cross-platform colored terminal text in Python - Python 3.x ii python3-commandnotfound 23.04.0 all Python 3 bindings for command-not-found. ii python3-configobj 5.0.8-3 all simple but powerful config file reader and writer for Python 3 ii python3-cryptography 41.0.7-4ubuntu0.1 amd64 Python library exposing cryptographic recipes and primitives (Python 3) ii python3-cups:amd64 2.0.1-5build6 amd64 Python3 bindings for CUPS ii python3-cupshelpers 1.5.18-1ubuntu9 all Python utility modules around the CUPS printing system ii python3-dateutil 2.8.2-3ubuntu1 all powerful extensions to the standard Python 3 datetime module ii python3-dbus 1.3.2-5build3 amd64 simple interprocess messaging system (Python 3 interface) ii python3-debconf 1.5.86ubuntu1 all interact with debconf from Python 3 ii python3-debian 0.1.49ubuntu2 all Python 3 modules to work with Debian-related data formats ii python3-defer 1.0.6-2.1ubuntu1 all Small framework for asynchronous programming (Python 3) ii python3-distro 1.9.0-1 all Linux OS platform information API ii python3-distro-info 1.7build1 all information about distributions' releases (Python 3 module) ii python3-distupgrade 1:24.04.26 all manage release upgrades ii python3-gdbm:amd64 3.12.3-0ubuntu1 amd64 GNU dbm database support for Python 3.x ii python3-gi 3.48.2-1 amd64 Python 3 bindings for gobject-introspection libraries ii python3-httplib2 0.20.4-3 all comprehensive HTTP client library written for Python3 ii python3-ibus-1.0 1.5.29-2 all Intelligent Input Bus - introspection overrides for Python (Python 3) ii python3-idna 3.6-2ubuntu0.1 all Python IDNA2008 (RFC 5891) handling (Python 3) ii python3-jinja2 3.1.2-1ubuntu1.2 all small but fast and easy to use stand-alone template engine ii python3-json-pointer 2.0-0ubuntu1 all resolve JSON pointers - Python 3.x ii python3-jsonpatch 1.32-3 all library to apply JSON patches - Python 3.x ii python3-jsonschema 4.10.3-2ubuntu1 all An(other) implementation of JSON Schema (Draft 3, 4, 6, 7) ii python3-jwt 2.7.0-1 all Python 3 implementation of JSON Web Token ii python3-launchpadlib 1.11.0-6 all Launchpad web services client library (Python 3) ii python3-lazr.restfulclient 0.14.6-1 all client for lazr.restful-based web services (Python 3) ii python3-lazr.uri 1.0.6-3 all library for parsing, manipulating, and generating URIs ii python3-louis 3.29.0-1build1 all Python bindings for liblouis ii python3-markdown-it 3.0.0-2 all Python port of markdown-it and some its associated plugins ii python3-markupsafe 2.1.5-1build2 amd64 HTML/XHTML/XML string library ii python3-mdurl 0.1.2-1 all Python port of the JavaScript mdurl package ii python3-minimal 3.12.3-0ubuntu2 amd64 minimal subset of the Python language (default python3 version) ii python3-netaddr 0.8.0-2ubuntu1 all manipulation of various common network address notations (Python 3) ii python3-netifaces:amd64 0.11.0-2build3 amd64 portable network interface information - Python 3.x ii python3-netplan 1.1.1-1~ubuntu24.04.1 amd64 Declarative network configuration Python bindings ii python3-oauthlib 3.2.2-1 all generic, spec-compliant implementation of OAuth for Python3 ii python3-olefile 0.46-3 all Python module to read/write MS OLE2 files ii python3-pexpect 4.9-2 all Python 3 module for automating interactive applications ii python3-pil:amd64 10.2.0-1ubuntu1 amd64 Python Imaging Library (Python3) ii python3-pkg-resources 68.1.2-2ubuntu1.1 all Package Discovery and Resource Access using pkg_resources ii python3-problem-report 2.28.1-0ubuntu3.3 all Python 3 library to handle problem reports ii python3-ptyprocess 0.7.0-5 all Run a subprocess in a pseudo terminal from Python 3 ii python3-pygments 2.17.2+dfsg-1 all syntax highlighting package written in Python 3 ii python3-pyparsing 3.1.1-1 all alternative to creating and executing simple grammars - Python 3.x ii python3-pyrsistent:amd64 0.20.0-1build2 amd64 persistent/functional/immutable data structures for Python ii python3-requests 2.31.0+dfsg-1ubuntu1 all elegant and simple HTTP library for Python3, built for human beings ii python3-rich 13.7.1-1 all render rich text, tables, progress bars, syntax highlighting, markdown and more ii python3-serial 3.5-2 all pyserial - module encapsulating access for the serial port ii python3-six 1.16.0-4 all Python 2 and 3 compatibility library ii python3-software-properties 0.99.49.1 all manage the repositories that you install software from ii python3-speechd 0.12.0~rc2-2build3 all Python interface to Speech Dispatcher ii python3-sss 2.9.4-1.1ubuntu6.2 amd64 Python3 module for the System Security Services Daemon ii python3-systemd 235-1build4 amd64 Python 3 bindings for systemd ii python3-typing-extensions 4.10.0-1 all Backported and Experimental Type Hints for Python ii python3-tz 2024.1-2 all Python3 version of the Olson timezone database ii python3-update-manager 1:24.04.9 all Python 3.x module for update-manager ii python3-urllib3 2.0.7-1ubuntu0.1 all HTTP library with thread-safe connection pooling for Python3 ii python3-wadllib 1.3.6-5 all Python 3 library for navigating WADL files ii python3-xdg 0.28-2 all Python 3 library to access freedesktop.org standards ii python3-xkit 0.5.0ubuntu6 all library for the manipulation of xorg.conf files (Python 3) ii python3-yaml 6.0.1-2build2 amd64 YAML parser and emitter for Python3 ii python3.12 3.12.3-1ubuntu0.4 amd64 Interactive high-level object-oriented language (version 3.12) ii python3.12-minimal 3.12.3-1ubuntu0.4 amd64 Minimal subset of the Python language (version 3.12) root@zhang:~# sudo apt remove python3.12
最新发布
06-07
<think>我们首先需要明确:用户想要卸载通过apt安装的Python3.12版本,同时避免影响系统依赖。根据之前的引用内容,Python3.12可能是通过两种方式安装的:1)从deadsnakesPPA安装;2)从源码编译安装。但用户明确要求使用apt命令卸载,所以我们假设是通过PPA安装的。同时注意:引用[4]中提到“不推荐将python3.12替代系统自带版本,这样会导致系统本身出现错误。”,所以我们卸载时要确保只卸载Python3.12,而不影响系统默认的Python(如Python3.10或3.8)。步骤:1.确认Python3.12是通过apt安装的(即通过deadsnakesPPA安装)2.使用apt命令卸载Python3.12及其相关包3.移除可能存在的替代版本链接(如果用户按照引用[2]设置了update-alternatives)4.清理依赖(可选)但是,卸载时需要注意:不要卸载任何系统默认的Python版本,也不要卸载其他可能依赖的包。具体操作:步骤1:卸载Python3.12命令:`sudoaptremovepython3.12`步骤2:卸载与Python3.12相关联的包,例如python3.12-venv(如果安装了)命令:`sudoaptremovepython3.12-venvpython3.12-dev`#根据实际情况,用户可能还安装了其他如dev包,但一般venv包是常见的但是,我们也可以使用自动删除来清理不再需要的依赖(注意:这个操作可能会删除一些其他包,所以建议先查看将被删除的包列表):命令:`sudoaptautoremove`步骤3:如果之前使用update-alternatives设置了python的替代版本,需要手动移除命令:`sudoupdate-alternatives--removepython/usr/bin/python3.12`但是,注意:在引用[2]中,添加替代版本时使用的是:sudoupdate-alternatives--install/usr/bin/pythonpython/usr/bin/python3.121因此,移除时使用上述命令即可。然而,如果用户并没有设置替代版本,那么这一步可以省略。步骤4:如果不再需要deadsnakesPPA,可以移除(可选)移除PPA并不会卸载已经安装的软件,但会阻止后续更新。移除命令:sudoadd-apt-repository--removeppa:deadsnakes/ppa注意:如果系统中还有其他来自deadsnakesPPA的Python版本,则不建议移除PPA。但是,用户仅要求卸载Python3.12,所以我们只卸载该版本。安全提示:在执行卸载前,建议先确认当前系统默认的Python版本(使用`python3--version`或`python--version`),确保我们不会影响到默认版本。完整步骤:1.检查已安装的Python3.12相关包dpkg--list|greppython3.122.卸载Python3.12主包sudoaptremovepython3.123.卸载与Python3.12关联的其他包(比如venv,dev等)sudoaptremovepython3.12-*4.自动移除不需要的包(可选,但建议先检查列表)sudoaptautoremove5.移除替代链接(如果有)sudoupdate-alternatives--removepython/usr/bin/python3.12注意:第3步中使用通配符卸载所有以python3.12开头的包,这样确保清理干净。但是,在执行sudoaptremovepython3.12-*时要小心,确保这些包确实可以卸载,不会误删其他版本。由于用户是通过apt安装的,所以使用apt卸载是安全的。另外,在引用[5]中提到在Ubuntu24.04中,有些库是通过apt安装的(如python3-pycryptodome),但这里我们只卸载Python3.12,不会影响这些库,因为这些库是安装在系统Python环境中的(可能是系统默认Python)。但是,有一点要注意:如果用户使用Python3.12创建了虚拟环境,这些虚拟环境在卸载Python3.12后将无法使用,需要用户自行删除。最后,我们提供详细的步骤:</think> ### 如何在 Ubuntu 上安全卸载 Python 3.12 根据引用内容,Python 3.12 主要通过两种方式安装: - **PPA安装**(deadsnakes PPA)[^3][^4] - **源码编译安装**[^1][^2] 以下是针对不同安装方式的卸载方法: --- #### 🛑 方法 1:卸载通过 PPA 安装的 Python 3.12 ```bash # 1. 卸载 Python 3.12 主程序 sudo apt remove python3.12 # 2. 卸载关联包(venv等) sudo apt remove python3.12-venv python3.12-dev # 3. 清理残留配置 sudo apt autoremove --purge ``` #### ⚠️ 注意事项 1. **避免误删系统 Python**: ```bash # 查看系统默认 Python 版本(通常为 python3.10/python3.8) ls /usr/bin/python3.* ``` 切勿卸载系统默认 Python(如 `python3.10`),否则会导致系统崩溃[^4] 2. **移除替代链接**(如果设置过): ```bash sudo update-alternatives --remove python /usr/bin/python3.12 ``` --- #### 🔧 方法 2:卸载源码编译安装的 Python 3.12 ```bash # 1. 定位安装目录(通常为 /usr/local/bin/python3.12) which python3.12 # 2. 删除安装文件 sudo rm -rf /usr/local/bin/python3.12* sudo rm -rf /usr/local/lib/python3.12 # 3. 删除符号链接 sudo rm -f /usr/local/bin/pip3.12 sudo rm -f /usr/local/bin/idle3.12 # 4. 清理源码目录(如存在) cd ~ && rm -rf Python-3.12.0* ``` --- #### 🧹 卸载后检查 ```bash # 验证是否卸载成功 python3.12 --version # 应显示 "command not found" # 检查关联库(如Crypto/Pandas等库是否受影响) apt list --installed | grep python3.12 ``` --- #### ⚠️ 重要安全提示 1. **切勿卸载系统默认 Python**(如 `python3.10` 或 `python3.8`),否则会导致系统崩溃[^4][^2] 2. 虚拟环境不影响系统安全,可直接删除相关目录: ```bash rm -rf ~/.venv # 删除用户虚拟环境 ``` 3. 通过 APT 安装的 Python 库(如 `python3-pandas`)会自动随 Python 卸载[^5] 4. **PPA 保留问题**:若不再需要,可移除 PPA 源: ```bash sudo add-apt-repository --remove ppa:deadsnakes/ppa ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值