A Simple Extension: nautilus-python Reference Manual

## A Simple Extension

Create an empty file with the following code:

Example 1. A Simple Extension

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    from gi.repository import Nautilus, GObject
    from typing import List

    class TestExtension(GObject.GObject, Nautilus.MenuProvider):
        def __init__(self):
            super().__init__()
            print("Initialized test extension")

        def menu_activate_cb(
            self,
            menu: Nautilus.MenuItem,
            file: Nautilus.FileInfo,
        ) -> None:
            print("menu_activate_cb", file)

        def get_file_items(
            self,
            files: List[Nautilus.FileInfo],
        ) -> List[Nautilus.MenuItem]:
            if len(files) != 1:
                return []

            file = files[0]

            item = Nautilus.MenuItem(
                name="SimpleMenuExtension::Show_File_Name",
                label="Showing %s" % file.get_name(),
            )
            item.connect("activate", self.menu_activate_cb, file)

            return [
                item,
            ]

        # Even though we're not using background items, Nautilus will generate
        # a warning if the method isn't present
        def get_background_items(
            self,
            current_folder: Nautilus.FileInfo,
        ) -> List[Nautilus.MenuItem]:
            return []

Save this file as TestExtension.py in the ~/.local/share/nautilus-python/extensions folder. You may need to create this folder. To run, simply restart Nautilus.

Once Nautilus restarts, right-click on a file and you should see a new menu item, "Showing #filename#". It is as simple as that!

As mentioned above, in order to get loaded by Nautilus, a python extension must import the Nautilus module from gi.repository, create a class derived from a nautilus *Provider and a gobject.GObject, and create the methods that will be called by Nautilus when it requests information from its providers. In this case, when someone right-clicks on a file, Nautilus will ask all of its MenuProviders for additional menu items to show the user. When folders or files are clicked, the get_file_items method is called and a list of Nautilus.MenuItems is expected.