DESKTOP-ENTRY-LIB(1)

NAME
desktop-entry-lib - desktop-entry-lib 5.0

INTRODUCTION

desktop-entry-lib allows reading and writing .desktop files according to the Desktop Entry Specification <https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html>.

  Installation

You can install desktop-entry-lib like any other package with pip:

    pip install -U desktop-entry-lib

Since desktop-entry-lib is only a single file <https://gitlab.com/JakobDev/desktop-entry-lib/-/blob/main/desktop_entry_lib/__init__.py>, you can also just copy it into your project.

  Supported OS

desktop-entry-lib is primarily made for Linux and other OS, that support the Desktop Entry Specification, but it also works on other OS like Windows. It will miss a few fOS dependent features like reading all files from your Desktop, but the rest is working, so you can use it the create .desktop files for Linux for your project, even if you use a other OS.

  Validation

If you want to use the validation, you need desktop-file-validate to be installed and in PATH.

TUTORIAL

  Getting Started

desktop-entry-lib allows reading and writing .desktop files.

The class for handling desktop entries is the DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry> class. You can create a new empty DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry> be creating a new instance of the class, or you can load a existing one with these 3 classmethods:

•   from_string() <#desktop_entry_lib.__init__.DesktopEntry.from_string>: This functions takes the content of a .desktop file as argument.

•   from_file() <#desktop_entry_lib.__init__.DesktopEntry.from_file>: This function takes the path to a .desktop file as argument.

•   from_id() <#desktop_entry_lib.__init__.DesktopEntry.from_id>: This function searches all the places of your system, where desktop usually life. If it found one with the id (e.g. the ID is org.example.app, it will search for org.example.app.desktop) it will load it.

    The class Attributes of the class are the Keys of the desktop entry. e.g. If you want to access the value of the Key Type, you use my_object.Type. If a desktop entry does not have this Key, what can happens if a Key is optional, the Value will be None.

  Start Program

The get_command() <#desktop_entry_lib.__init__.DesktopEntry.get_command> function returns the command to start a program. It takes 2 arguments, which you can use to specify what this program should open:

1.  A list of local paths. The paths should be absolute. Every path is also treated as a file:// URL.

2.  A list of URLs. Every file:// URL is also treated as local path.

    You can run the command using the subprocess module <https://docs.python.org/3/library/subprocess.html> . You should also set the working directory to the value that you get with get_working_directory() <#desktop_entry_lib.__init__.DesktopEntry.get_working_directory>.

    Here's a simple example:

        entry = desktop_entry_lib.DesktopEntry.from_file("my_app.desktop")
        command = entry.get_command()
        subprocess.run(command, cwd=entry.get_working_directory())

    You can also take a look at the more complex example <>.

  Start in Terminal

You may now, that Desktop Entries can set the Terminal <#desktop_entry_lib.__init__.DesktopEntry.Terminal> Key to True, to indicate, that the Program should be started in a Terminal. Unfortunately there is no Way to get the default Terminal Emulator that works on all Distros and all Desktop Environments, so this is not supported by desktop-entry-lib.

On Debian based Distros, you could use x-terminal-emulator, which is a symlink to the default Terminal Emulator. On other Distros you could try to read the XDG_CURRENT_DESKTOP Environment variable to get the current Desktop Environment and launch the default Terminal Emulator e.g. Konsole on KDE. This does of course not work for every DE out there. If you use desktop-entry-lib just for personal scripts, this won't be a problem, since you should know which terminal EMulator you are using on your PC.

You can launch a given command on the most terminal Emulators using the -e argument. So if you find the Terminal Emulator, you should be able to start the Program in the Emulator using this.

    subprocess.run(["your-terminal-emulator", "-e", entry.get-command()] cwd=entry.get_working_directory())

  Drawbacks

Starting Programs with desktop-entry-lib works, but has a few drawbacks compared to launching it with you Desktop Environment:

•   The Terminal <#desktop_entry_lib.__init__.DesktopEntry.Terminal> Key is ignored. See above for a detailed explanation.

•   Even if a Program supports starting with D-Bus <https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#dbus>, it is still started with the Command.

•   Your Desktop Environment may not know, which Desktop Entry belongs to the started Program, so Options like SingleMainWindow <#desktop_entry_lib.__init__.DesktopEntry.SingleMainWindow> or the Actions <> might be ignored.

  Translations

As you should know, some keys of desktop entries can be translated. desktop entry-lib provides the TranslatableKey <#desktop_entry_lib.__init__.TranslatableKey> class to support this.

TranslatableKey class has 2 attributes:

•   default_text <#desktop_entry_lib.__init__.TranslatableKey.default_text>: This is a string which contains the non translated text.

•   translations <#desktop_entry_lib.__init__.TranslatableKey.translations>: This is a dict, which has the language as key and the text as value

    Take for example this part of a desktop entry:

        Name=MyApp
        Name[de]=MyAppGerman
        Name[fr]=MyAppFrench

    If you load this, with desktop-entry-lib, the default_text attribute would be MyApp and the translations dict would have the 2 keys de and fr with the corresponding value.

  Desktop Actions

Desktop entries can contain additional actions. Take for example this:

    [Desktop Entry]
    Type=Application
    Name=Test
    Actions=MyAction;
    [Desktop Action MyAction]
    Name=Example Action

Each instance of DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry> has a Actions attribute to support this. It is a dict. The Key is the internal name (in this case MyAction). The value is a instance of DesktopAction <#desktop_entry_lib.__init__.DesktopAction>, which can basically be used the same way as DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>.

  Collection

desktop-entry-lib provides the DesktopEntryCollection <#desktop_entry_lib.__init__.DesktopEntryCollection> class. As the name suggests, it is a collection of desktop entries.

You begin by creating a new instance of DesktopEntryCollection <#desktop_entry_lib.__init__.DesktopEntryCollection>. There are 4 different ways to add Desktop Entries to the Collection.

•   load_file() <#desktop_entry_lib.__init__.DesktopEntryCollection.load_file>: This adds a single file to the Collection. It takes the path to the .desktop file as argument.

•   load_directory() <#desktop_entry_lib.__init__.DesktopEntryCollection.load_directory>: This adds all .desktop files in this directory to the Collection. It takes the path to the directory as argument.

•   load_menu() <#desktop_entry_lib.__init__.DesktopEntryCollection.load_menu>: This adds all .desktop files that you see in your Menu to the Collection.

•   load_desktop() <#desktop_entry_lib.__init__.DesktopEntryCollection.load_desktop>: This adds all .desktop files, that you have on your Desktop to the Collection.

    You can call this functions as often as you want and add as many DesktopEntries as you like.

    DesktopEntryCollection <#desktop_entry_lib.__init__.DesktopEntryCollection> has a attribute called desktop_entries <#desktop_entry_lib.__init__.DesktopEntryCollection.desktop_entries>. It is a dict. The Key is the ID of the file. It is determined by the file name. If a file is called org.example.app.desktop the ID will be org.example.app. If you load another file with the same name, the old one it will be overwritten in the Collection.

  Flatpak

desktop-entry-lib can be fully used inside a Flatpak <https://flatpak.org> container. If you just want read/write Desktop Entries, there's nothing you need to do.

  Loading Entries from them Menu

Please note that the XDG_DATA_DIRS Environment Variable from the Host is not available inside a Flatpak, so desktop-entry-lib will not find custom locations. The standard locations however are found. desktop-entry-lib detects when it runs inside a Flatpak and will use the default locations which are hardcoded. The Flatpak will need the following permissions to find all desktop entries:

    --filesystem=/var/lib/flatpak/exports/share/applications:ro
    --filesystem=xdg-data/flatpak/exports/share/applications:ro
    --filesystem=xdg-data/applications:ro
    --filesystem=/var/lib/flatpak/app:ro
    --filesystem=xdg-data/flatpak/app:ro
    --filesystem=host-etc:ro

After you grant this Permissions, load_menu() <#desktop_entry_lib.__init__.DesktopEntryCollection.load_menu> will work as expected. If you also want to load the Icons, you need the following additional permissions.

    --filesystem=/var/lib/flatpak/exports/share/icons:ro
    --filesystem=xdg-data/flatpak/exports/share/icons:ro

  Starting Programs

If you want to start a Program on the host, you need the --talk-name=org.freedesktop.Flatpak Permission. When you have this Permission, you can execute a Program on the Host with:

    entry = desktop_entry_lib.DesktopEntry.from_file("my_app.desktop")
    command = entry.get_command()
    subprocess.run(["flatpak-spawn", "--host"] + command, cwd=entry.get_working_directory())

If you want to open a File, please note that the Paths you have inside your Flatpak may differ from the Paths on your Host.

  Install with Portal

desktop-entry-lib allows you to directly install a Desktop Entry using the DynamicLauncher Portal <https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.DynamicLauncher.html>. This Portal should be working out of the box on any major Distro. You need jeepney <https://pypi.org/project/jeepney> installed to use the Portal. You also need a Icon and a ID.

First you need to load the Icon as bytes. It must be a png or jpeg no larger than 512x512, or an svg.

    with open("/path/to/my/icon", "rb") as f:
        icon = f.read()

Now, you need to create the Entry that you want to install.

    entry = desktop_entry_lib.DesktopEntry()
    entry.Name.default_text = "My Name"
    entry.desktop_id = "com.example.App.Entry"
    entry.Exec = "my-app"

The desktop_id needs to start with the ID of your App e.g. If your AppID is com.example.App you can use com.example.App.Entry but not com.example.Entry. If you are not sure, just try any ID. You will get an error message that tells you what ID is allowed.

Now you just need to call install_with_portal() <#desktop_entry_lib.__init__.DesktopEntry.install_with_portal> with a Window Identifier <https://flatpak.github.io/xdg-desktop-portal/docs/window-identifiers.html>. and your Icon. If you don't have a Window Identifier, just use an empty string. If an error occurs, install_with_portal() <#desktop_entry_lib.__init__.DesktopEntry.install_with_portal> will throw a InstallWithPortalError <#desktop_entry_lib.__init__.InstallWithPortalError> exception. If the User cancels the Installation, a InstallWithPortalsCanceled <#desktop_entry_lib.__init__.InstallWithPortalsCanceled> exception is thrown. If the DynamicLauncher Portal is not available, InstallWithPortalsNotAvailable <#desktop_entry_lib.__init__.InstallWithPortalsNotAvailable> is thrown. If everything worked, it returns a dict that contains the Name and the Icon.

    try:
        entry.install_with_portal("", icon)
    except desktop_entry_lib.InstallWithPortalsNotAvailable:
        print("The DynamicLauncher portal is not available")
    except desktop_entry_lib.InstallWithPortalError as ex:
        print(ex.message)
    except desktop_entry_lib.InstallWithPortalsCanceled:
        print("The user canceled the installation")

A dialog should appear, allowing the user to install the entry. install_with_portal() <#desktop_entry_lib.__init__.DesktopEntry.install_with_portal> has the 2 Keywords arguments editable_name and editable_icon, which allows to control if the User can edit the Name/Icon in the dialog. These arguments are not guaranteed to work on every desktop.

You should also take a look at the complete example <>.

API

get_xdg_data_dirs() -> list[str]
    Get all XDG DATA DIRS

Returns
    The list of XDG data Dirs

Return type
    list[str]

get_icon_path(icon_name: str) -> str | None
    Get the path of a Icon

Parameters
    icon_name (str) -- The name of the Icon as found in the desktop entry

Returns
    The full path to the Icon. none if the Icon was not found.

Return type
    str | None

is_action_identifier_valid(identifier: str) -> bool
    Checks if a Action identifier is valid

Parameters
    identifier (str) -- The Identifier

Returns
    If the identifier is valid

Return type
    bool

is_custom_key_name_valid(name: str) -> bool
    Checks if the given name can be used for a custom key

Parameters

•   identifier -- The name

•   name (str)

Returns
    If the name can be used

Return type
    bool

class ValidationMessageDict
    Defines the return type for get_validation_messages()

Error: list[str]

FutureError: list[str]

Warning: list[str]

Hint: list[str]

class InstallWithPortalResponse
    Defines the return type for install_with_portal()

Name: str

Icon: bytes

exception InstallWithPortalsNotAvailable
    Raised by install_with_portal() when the DynamicLauncher portal is not available

Return type
    None

exception InstallWithPortalError(message: str)
    Raised by install_with_portal() when an error occures

Parameters
    message (str)

Return type
    None

exception InstallWithPortalsCanceled
    Raised by install_with_portal() when the User canceled the Installation

Return type
    None

exception InvalidDesktopEntry
    This Exception is raised, when a invalid Desktop Entry is loaded

Return type
    None

class TranslatableKey
    Represents a Key in a Desktop Entry, that can be translated into different languages

default_text: str
    The untranslated text

translations: dict[str, str]
    The translations

get_translated_text() -> str
    Returns the text for the current system language

Returns
    The text

Return type
    str

load_section(section: dict[str, str], search_key: str) -> None
    Loads a section from a Desktop Entry. Only for internal use.

Parameters

•   section (dict[str, str])

•   search_key (str)

Return type
    None

get_text(entry_key: str) -> str
    Returns the text for saving a Desktop Entry. only for internal use.

Parameters
    entry_key (str)

Return type
    str

clear() -> None
    Clear

Return type
    None

class TranslatableListKey
    Represents a List in a Desktop Entry, that can be translated into different languages

default_list: list[str]
    The unstranslated list

translations: dict[str, list[str]]
    The translated lists

load_section(section: dict[str, str], search_key: str) -> None
    Loads a section from a Desktop Entry. Only for internal use.

Parameters

•   section (dict[str, str])

•   search_key (str)

Return type
    None

get_text(entry_key: str) -> str
    Returns the text for saving a Desktop Entry. only for internal use.

Parameters
    entry_key (str)

Return type
    str

clear() -> None
    Clear

Return type
    None

class DesktopAction
    Represents a Action in a Desktop Entry

Name: TranslatableKey <#desktop_entry_lib.__init__.TranslatableKey>
    The Name Key

Icon: str | None
    The Icon Key

Exec: str | None
    The Exec Key

classmethod from_dict(action_section: dict[str, str])
    Load the Action from a Dict. Onyl used internaly.

Parameters
    action_section (dict[str, str])

get_text() -> str
    Converts the Action into a String

Return type
    str

get_icon_path() -> str | None
    Returns full Path to the Icon

Returns
    The full Path or None, if the Icon can't be found

Return type
    str | None

get_command(file_list: list[str] | None = None, url_list: list[str] | None = None) -> list[str]
    Returns the command to start this action. Returns an empty list if the Exec Key is not set. Take a look at the tutorial <> for more information.

Parameters

•   file_list (list[str] | None) -- A list of local files

•   url_list (list[str] | None) -- A list of URLs

Returns
    The command

Return type
    list[str]

class DesktopEntry
    Represents a Desktop Entry

Type: Literal['Application', 'Link', 'Directory']
    The Type Key

Version: Literal['1.0', '1.1', '1.2', '1.3', '1.4', '1.5'] | None
    The Version Key

Name: TranslatableKey <#desktop_entry_lib.__init__.TranslatableKey>
    The Name Key

GenericName: TranslatableKey <#desktop_entry_lib.__init__.TranslatableKey>
    The GenericName Key

NoDisplay: bool | None
    The NoDisplay Key

Comment: TranslatableKey <#desktop_entry_lib.__init__.TranslatableKey>
    The Comment Key

Icon: str | None
    The Icon Key

Hidden: bool | None
    The Hidden Key

OnlyShowIn: list[str]
    The OnlyShowIn Key

NotShowIn: list[str]
    The NotShowIn Key

DBusActivatable: bool | None
    The DBusActivatable Key

TryExec: str | None
    The TryExec Key

Exec: str | None
    The Exec Key

Path: str | None
    The Path Key

Terminal: bool | None
    The Terminal Key

MimeType: list[str]
    The MimeType Key

Categories: list[str]
    The Categories Key

Implements: list[str]
    The Implements Key

Keywords: TranslatableListKey <#desktop_entry_lib.__init__.TranslatableListKey>
    The Keywords Key

StartupNotify: bool | None
    The StartupNotify Key

StartupWMClass: str | None
    The StartupWMClass Key

URL: str | None
    The URL Key

PrefersNonDefaultGPU: bool | None
    The PrefersNonDefaultGPU Key

SingleMainWindow: bool | None
    The SingleMainWindow Key

Actions: dict[str, DesktopAction <#desktop_entry_lib.__init__.DesktopAction>]
    The Actions

CustomKeys: dict[str, str]
    The Keys starting with X-

file_path: str | None
    The path to the .desktop file

desktop_id: str | None
    The ID of the .desktop file

leading_comment: str | None
    If you set this, the given Comment will be added at the top of the Desktop Entry. You can use it for stuff like 'Created with foo'.

is_valid() -> bool
    Returns, if the Desktop Entry is valid. desktop-file-validate needs to be installed.

Returns
    If the entry is valid

Return type
    bool

get_validation_messages() -> ValidationMessageDict <#desktop_entry_lib.__init__.ValidationMessageDict>
    Returns all messages from desktop-file-validate

Returns
    A dict which contains the validation messages

Return type
    ValidationMessageDict <#desktop_entry_lib.__init__.ValidationMessageDict>

should_show() -> bool
    Returns if Desktop Entry should be showed

Return type
    bool

should_show_in_menu() -> bool
    Returns if a dektop entry should be displayed in the menu

Return type
    bool

get_icon_path() -> str | None
    Returns the full path to the Icon

Return type
    str | None

get_working_directory() -> str
    Returns the working directory for this program. When the Path Key is set, the value of this Key is returned. If not, the Home directory is returned.

Returns
    The working directory

Return type
    str

get_command(file_list: list[str] | None = None, url_list: list[str] | None = None) -> list[str]
    Returns the command to start this program. Returns an empty list if the Exec Key is not set. Take a look at the tutorial <> for more information.

Parameters

•   file_list (list[str] | None) -- A list of local files

•   url_list (list[str] | None) -- A list of URLs

Returns
    The command

Return type
    list[str]

is_empty() -> bool
    Checks if the Desktop Entry is empty

Return type
    bool

get_text() -> str
    Returns the content of the Desktop Entry

Return type
    str

write_file(path: str | PathLike) -> None
    Writes a .desktop file

Parameters
    path (str | PathLike)

Return type
    None

install_with_portal(window_dentifier: str, icon: bytes, *, editable_name: bool = True, editable_icon: bool = False) -> InstallWithPortalResponse <#desktop_entry_lib.__init__.InstallWithPortalResponse>
    Installs the entry using the DynamicLauncher Portal <https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.DynamicLauncher.html>. Take a look at the tutorial <> for more information.

Parameters

•   window_dentifier (str) -- The Window Identifier <https://flatpak.github.io/xdg-desktop-portal/docs/window-identifiers.html>

•   icon (bytes) -- The Icon

•   editable_name (bool) -- If the User should be able to edit the Name, defaults to True

•   editable_icon (bool) -- If the User should be able to edit the Icon, defaults to False

Raises

•   InstallWithPortalsNotAvailable <#desktop_entry_lib.__init__.InstallWithPortalsNotAvailable> -- The DynamicLauncher portal is not available

•   InstallWithPortalError <#desktop_entry_lib.__init__.InstallWithPortalError> -- A error occured

•   InstallWithPortalsCanceled <#desktop_entry_lib.__init__.InstallWithPortalsCanceled> -- The user canceled the Installation

•   ModuleNotFoundError -- jeepney is not installed

Returns
    The name and the icon of the shortcut

Return type
    InstallWithPortalResponse <#desktop_entry_lib.__init__.InstallWithPortalResponse>

classmethod from_string(text: str) -> DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>
    Loads the content of a .desktop file from a string

Parameters
    text (str)

Return type
    DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>

classmethod from_file(path: str | PathLike) -> DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>
    Returns a Desktop Entry from the given file

Parameters
    path (str | PathLike)

Return type
    DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>

classmethod from_id(desktop_id: str) -> DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry> | None
    Returns a Desktop Entry from the given id

Parameters
    desktop_id (str)

Return type
    DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry> | None

static get_keywords() -> list[str]
    Returns the list of Keywords of a Desktop Entry

Returns
    The list of Keys

Return type
    list[str]

class DesktopEntryCollection
    Represents a Collection of multiple Desktop Entries

desktop_entries: dict[str, DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>]
    The desktop entries

load_file(path: str | PathLike) -> None
    Loads the given desktop entry file and adds it to the collection

Parameters
    path (str | PathLike) -- The path to the desktop entry

Return type
    None

load_directory(path: str | PathLike) -> bool
    Loads all desktop entries from the given directory

Parameters
    path (str | PathLike) -- The directory

Returns
    True if all desktop entries could be loaded, False if some couldn't be loaded

Return type
    bool

load_menu() -> bool
    Loads all desktop entries from the menu

Returns
    True if all desktop entries could be loaded, False if some couldn't be loaded

Return type
    bool

load_desktop() -> bool
    Loads all desktop entries files from the Desktop

Returns
    True if all desktop entries could be loaded, False if some couldn't be loaded

Return type
    bool

load_autostart() -> bool
    Loads all autostart entries

Returns
    True if all desktop entries could be loaded, False if some couldn't be loaded

Return type
    bool

get_entries_by_category(category: str) -> list[DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>]
    Returns a list of all desktop entries that have the given category

Parameters
    category (str) -- The category

Returns
    The list of desktop entries

Return type
    list[DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>]

get_entries_by_mime_type(mime_type: str) -> list[DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>]
    Returns a list of all desktop entries that can open the given MimeType

Parameters
    mime_type (str) -- The MimeType

Returns
    The list of desktop entries

Return type
    list[DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>]

get_visible_entries() -> list[DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>]
    Returns a list of all desktop entries that should be shown to the User

Returns
    The list of desktop entries

Return type
    list[DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>]

get_menu_entries() -> list[DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>]
    Returns a list of all desktop entries that should be shown in the Menu

Returns
    The list of desktop entries

Return type
    list[DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry>]

get_entry_by_name(name: str, include_translations: bool = True) -> DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry> | None
    Returns the entry with the given Name. Returns None if no Entry exists with this Name.

Parameters

•   name (str) -- The Name

•   include_translations (bool) -- Search also the translations

Returns
    The Entry

Return type
    DesktopEntry <#desktop_entry_lib.__init__.DesktopEntry> | None

EXAMPLES

  WriteFile

    import desktop_entry_lib
    def main() -> None:
        entry = desktop_entry_lib.DesktopEntry()
        entry.Name.default_text = "My App"
        entry.Comment.default_text = "A short description"
        entry.Comment.translations["de"] = "A short german description"
        entry.Type = "Application"
        entry.Exec = "my-app"
        entry.write_file("my_app.desktop")
    if __name__ == "__main__":
        main()

View this example on Codeberg <https://codeberg.org/JakobDev/desktop-entry-lib/src/branch/master/examples/WriteFile.py>

  InstallWithPortal

    import desktop_entry_lib
    import sys
    def main() -> None:
        entry = desktop_entry_lib.DesktopEntry()
        entry.Name.default_text = "My Name"
        entry.desktop_id = "com.example.App.Entry"
        entry.Exec = "firefox"
        path = input("Please enter the path to an icon file:")
        if path == "":
            print("You haven't entered a path", file=sys.stderr)
            sys.exit(1)
        try:
            with open(path, "rb") as f:
                icon = f.read()
        except FileNotFoundError:
            print(f"{path} was not found", file=sys.stderr)
            sys.exit(1)
        try:
            response = entry.install_with_portal("", icon)
        except ModuleNotFoundError:
            print('jeepney is not installed. Run "pip install jeepney"', file=sys.stderr)
            sys.exit(1)
        except desktop_entry_lib.InstallWithPortalsNotAvailable:
            print("The DynamicLauncher portal is not available", file=sys.stderr)
            sys.exit(1)
        except desktop_entry_lib.InstallWithPortalError as ex:
            print(f"An error occurred: {ex.message}", file=sys.stderr)
            sys.exit(1)
        except desktop_entry_lib.InstallWithPortalsCanceled:
            print("The user canceled the installation", file=sys.stderr)
            sys.exit(1)
        print(f"Your desktop entry was successfully installed with the name {response['Name']}.")
    if __name__ == "__main__":
        main()

View this example on Codeberg <https://codeberg.org/JakobDev/desktop-entry-lib/src/branch/master/examples/InstallWithPortal.py>

  Collection

    import desktop_entry_lib
    def main() -> None:
        collection = desktop_entry_lib.DesktopEntryCollection()
        # Load all desktop entries from the Menu into the Collection
        collection.load_menu()
        print("This Apps can open HTML files:")
        for i in collection.get_entries_by_mime_type("text/html"):
            print(i.Name.get_translated_text())
        # Check if desktop entry is in the Collection
        if "org.example.app" not in collection:
            print("org.example.app was not found")
            return
        # Do something with the entry
        print(collection["org.example.app"].Name.get_translated_text())
    if __name__ == "__main__":
        main()

View this example on Codeberg <https://codeberg.org/JakobDev/desktop-entry-lib/src/branch/master/examples/Collection.py>

  ReadFile

    import desktop_entry_lib
    def main() -> None:
        entry = desktop_entry_lib.DesktopEntry.from_file("my_app.desktop")
        print("Name: " + entry.Name.default_text)
        print("Comment: " + entry.Comment.default_text)
        print("German translation for Comment: " + entry.Comment.translations.get("de", "None"))
        print("Type: " + entry.Type)
        print("Exec: " + entry.Exec)
    if __name__ == "__main__":
        main()

View this example on Codeberg <https://codeberg.org/JakobDev/desktop-entry-lib/src/branch/master/examples/ReadFile.py>

  StartProgram

    import desktop_entry_lib
    import subprocess
    import sys
    import os
    def start_firefox() -> None:
        collection = desktop_entry_lib.DesktopEntryCollection()
        collection.load_menu()
        if "org.mozilla.firefox" not in collection:
            print("Firefox was not found", file=sys.stderr)
            return
        entry = collection["org.mozilla.firefox"]
        command = entry.get_command()
        subprocess.run(command, cwd=entry.get_working_directory())
    def open_url_in_firefox() -> None:
        collection = desktop_entry_lib.DesktopEntryCollection()
        collection.load_menu()
        if "org.mozilla.firefox" not in collection:
            print("Firefox was not found", file=sys.stderr)
            return
        entry = collection["org.mozilla.firefox"]
        command = entry.get_command(url_list=["https://example.com"])
        subprocess.run(command, cwd=entry.get_working_directory())
    def open_file_in_kate() -> None:
        collection = desktop_entry_lib.DesktopEntryCollection()
        collection.load_menu()
        if "org.kde.kate" not in collection:
            print("Kate was not found", file=sys.stderr)
            return
        entry = collection["org.kde.kate"]
        command = entry.get_command(file_list=[os.path.abspath("test.txt")])
        subprocess.run(command, cwd=entry.get_working_directory())
    def main() -> None:
        print("Select what you want to do by entering the number")
        print("1: Start Firefox")
        print("2: Open example.com in Firefox")
        print("3: Open test.txt in Kate")
        match input():
            case "1":
                start_firefox()
            case "2":
                open_url_in_firefox()
            case "3":
                open_file_in_kate()
            case _:
                print("Unsupported option", file=sys.stderr)
    if __name__ == "__main__":
        main()

View this example on Codeberg <https://codeberg.org/JakobDev/desktop-entry-lib/src/branch/master/examples/StartProgram.py>

  Action

    import desktop_entry_lib
    def write() -> None:
        entry = desktop_entry_lib.DesktopEntry()
        entry.Name.default_text = "My App"
        action = desktop_entry_lib.DesktopAction()
        action.Name.default_text = "My Action"
        entry.Actions["Example"] = action
        entry.write_file("my_app.desktop")
    def read() -> None:
        entry = desktop_entry_lib.DesktopEntry.from_file("my_app.desktop")
        print(entry.Actions["Example"].Name.default_text)
    if __name__ == "__main__":
        write()
        read()

View this example on Codeberg <https://codeberg.org/JakobDev/desktop-entry-lib/src/branch/master/examples/Action.py>

CHANGELOG

  5.0

•   Added install_with_portal() <#desktop_entry_lib.__init__.DesktopEntry.install_with_portal>

  4.2

•   Fix reading Implements

•   Fix writing DBusActivatable

  4.1

•   Write StartupWMClass with the correct key (strangejune <https://codeberg.org/strangejune>)

  4.0

•   Added get_command() <#desktop_entry_lib.__init__.DesktopEntry.get_command>

•   Added get_working_directory() <#desktop_entry_lib.__init__.DesktopEntry.get_working_directory>

•   Added get_entry_by_name() <#desktop_entry_lib.__init__.DesktopEntryCollection.get_entry_by_name>

•   Python 3.10 is now required

  3.2

•   Find more data directories when running as Flatpak

  3.1

•   Add return value to the load function of the Collection

  3.0

•   Move Project to Codeberg

•   Add InvalidDesktopEntry

•   Add is_action_identifier_valid() and is_custom_key_name_valid()

•   Add get_keywords() and is_empty() to DesktopEntry

  2.3

•   Add StartupWMClass key

•   Fix should_show_in_menu()

•   Allow : as suffix for path environment variables

  2.2

•   Save boolean values as lowercase

•   Fix DBusActivatable key

  2.1

•   Fix saving Terminal Key

  2.0

•   Add support for Actions

•   Add support for Flatpak

•   Implement magic methods

•   Implement validation

  1.0

•   First release

•   Index <>

•   Module Index <>

•   Search Page <>

Author
JakobDev

Copyright
2022-2024, JakobDev