PyXDG
PyXDG is a Python library that provides implementations of various freedesktop.org standards. These standards define common desktop operations and components, such as determining file MIME types, getting icons for applications, and accessing application menus. It is currently at version 0.28 and is actively maintained, with releases addressing compatibility and bug fixes.
Warnings
- breaking PyXDG version 0.27 fixed compatibility issues with Python >= 3.8.4, specifically regarding menu processing. Older versions might encounter `AttributeError` or unexpected behavior.
- deprecated The `Rule.compile()` method in `xdg.Menu` was removed in PyXDG 0.24. Code relying on this method will break.
- gotcha There is a known namespace collision with another package named `xdg` (which was later renamed to `xdg-base-dirs`). Installing both `pyxdg` and `xdg` (or `xdg-base-dirs`) might lead to import errors or unexpected behavior due to both trying to provide the `xdg` top-level package.
- gotcha The `xdg.BaseDirectory.get_runtime_dir()` method, when called with `strict=True` (the default), will not create the runtime directory if it doesn't exist or if permissions are incorrect, returning `None`. This can be a silent failure if not handled.
- gotcha When finding a file's MIME type, `xdg.Mime.get_type()` tries to use file contents and falls back to the name. If `name_pri` is set to 100 or higher, it prioritizes the filename. This can lead to incorrect MIME type detection if a file has a misleading extension and `name_pri` is not handled carefully.
Install
-
pip install pyxdg
Imports
- BaseDirectory
from xdg import BaseDirectory
- DesktopEntry
from xdg import DesktopEntry
- Mime
from xdg import Mime
- Menu
from xdg import Menu
- IconTheme
from xdg import IconTheme
Quickstart
import os
from xdg import BaseDirectory, Mime
# Get user's data home directory
data_home = BaseDirectory.xdg_data_home
print(f"XDG Data Home: {data_home}")
# Get preferred configuration directories
config_dirs = BaseDirectory.xdg_config_dirs
print(f"XDG Config Dirs: {config_dirs}")
# Find the MIME type of a file (example with a dummy file)
# Create a dummy file for demonstration
dummy_file_path = os.path.join(data_home, 'test.txt')
with open(dummy_file_path, 'w') as f:
f.write('Hello, PyXDG!')
mime_type = Mime.get_type(dummy_file_path)
print(f"MIME type of '{dummy_file_path}': {mime_type}")
# Clean up dummy file
os.remove(dummy_file_path)