我有一个使用 PyGTK (GTK+2) 编写的应用程序。我想通过扩展将它与 Nautilus 集成(我正在努力学习)。我当前的桌面有 GNOME3 和 Nautilus 3,它们是用 GTK+3 编写的,Nautilus 的扩展使用 PyGObject。
我可以将 GTK+2 中的应用程序与 Nautilus 3 集成吗?(尚未将我的应用程序移植到 GTK+3)。有什么提示吗?
我计划将我的应用程序移植到 GTK+3 (PyGObject),但它需要的时间比我现在要多。
是的,有可能。例如,您可以使用 Nautilus 以文件或目录作为参数来调用您的程序。您调用的程序可以用任何工具包编写,甚至可以只是一个 shell 脚本。
一个小例子或扩展:
from gi.repository import Nautilus, GObject
from urllib import unquote
PROGRAM_NAME = '/path/to/your/program'
class MyExtension(GObject.GObject, Nautilus.MenuProvider):
def __init__(self):
pass
def call_my_program(self, menu, files):
# Do whatever you want to do with the files selected
if len(files) == 0:
return
# Strip the URI format to plain file names
names = [ unquote(file.get_uri()[7:]) for file in files ]
argv = [ PROGRAM_NAME ] + names
GObject.spawn_async(argv, flags=GObject.SPAWN_SEARCH_PATH)
def get_file_items(self, window, files):
# Show the menu if there is at least on file selected
if len(files) == 0:
return
# We care only files (local files)
for fd in files:
if fd.is_directory() or fd.get_uri_scheme() != 'file':
return
item = Nautilus.MenuItem(name='MyExtensionID::MyMethodID',
label='Do something with my program...')
item.connect('activate', self.call_my_program, files)
return item,
该扩展是使用 GObject Introspection (Nautilus 3) 编写的,它是通用的:您可以调用任何您想要接受文件作为参数的外部程序。关键是GObject.spawn_async()
。
get_file_items
是 Nautilus 在用户与文件交互时调用的方法。在那里,您可以绑定上下文菜单(使用Nautilus.MenuItem()
)。然后,将该菜单与调用程序的方法(call_my_program()
)连接起来。
您可以在方法中创建其他过滤器get_file_items
。例如,仅在选择文本普通文件(使用)时才显示上下文菜单fd.is_mime_type()
。你可以做任何你想做的事。请注意只执行非阻塞操作,否则您可能会阻塞 Nautilus。
要测试扩展,您可以将其安装在~/.local/share/nautilus-python/extensions
.
检查内省移植:
请注意,您不能中途迁移:如果您尝试同时导入 gtk 和 gi.repository.Gtk,您将只得到程序挂起和崩溃,因为您正尝试以两种不同的方式使用同一个库. 不过,您可以混合使用不同库的静态和 GI 绑定,例如 dbus-python 和 gi.repository.Gtk。
因此,这取决于 Nautilus 插件的实现方式。