PyGTK: Copy a file to clipboard (paste it in Nautilus)
PyGTK provide clipboard functionality for standard targets: text, file(s) and image. Nautilus if does not use the standard URI target for copy/cat/paste file because this target does not provide the desired action (copy or cut).
For copy/cat/paste Nautilus use a special clipboard target named “x-special/gnome-copied-files”. The content of this target is a text with items separated by new line character (”\n”). The first line is the action (”copy” or “cut”) and then one URI per line.
To copy the file /path/abc.txt the target “x-special/gnome-copied-files” contains the text:
copy file:///path/abc.txt
The class “gtk.Clipboard” has the method
def set_with_data(targets, get_func, clear_func, user_data)
to set the content of the clipboard to any targets and to provide functions for clipboard requests (get/clean).
Using this method I write a simple code to handle copy path to clipboard (gnomeclipboardtools.py):
import pygtk pygtk.require("2.0") import gtk import gnomevfs def clipboard_copy_path( path ): targets = gtk.target_list_add_uri_targets() targets = gtk.target_list_add_text_targets( targets) targets.append( ( 'x-special/gnome-copied-files', 0, 0 ) ) clipboard = gtk.clipboard_get() clipboard.set_with_data( targets, __clipboard_copy_path_get, __clipboard_copy_path_clear, path ) clipboard.store() def __clipboard_copy_path_get( clipboard, selectiondata, info, path ): selectiondata.set_text( path ) path2 = gnomevfs.escape_path_string(path) selectiondata.set_uris( [ 'file://' + path2 ] ) selectiondata.set( 'x-special/gnome-copied-files', 8, 'copy\nfile://' + path2 ); def __clipboard_copy_path_clear( self, path ): return
Using it is very simple:
import gnomeclipboardtools gnomeclipboardtools.clipboard_copy_path( '/path/abc.txt' )
