Search code examples
pythonlinuxclipboard

Is there a way to directly send a python output to clipboard?


For example, if a python script will spit out a string giving the path of a newly written file that I'm going to edit immediately after running the script, it would be very nice to have it directly sent to the system clipboard rather than STDOUT.


Solution

  • You can use an external program, xsel:

    from subprocess import Popen, PIPE
    p = Popen(['xsel','-pi'], stdin=PIPE)
    p.communicate(input='Hello, World')
    

    With xsel, you can set the clipboard you want to work on.

    • -p works with the PRIMARY selection. That's the middle click one.
    • -s works with the SECONDARY selection. I don't know if this is used anymore.
    • -b works with the CLIPBOARD selection. That's your Ctrl + V one.

    Read more about X's clipboards here and here.

    A quick and dirty function I created to handle this:

    def paste(str, p=True, c=True):
        from subprocess import Popen, PIPE
    
        if p:
            p = Popen(['xsel', '-pi'], stdin=PIPE)
            p.communicate(input=str)
        if c:
            p = Popen(['xsel', '-bi'], stdin=PIPE)
            p.communicate(input=str)
    
    paste('Hello', False)    # pastes to CLIPBOARD only
    paste('Hello', c=False)  # pastes to PRIMARY only
    paste('Hello')           # pastes to both
    

    You can also try pyGTK's clipboard :

    import pygtk
    pygtk.require('2.0')
    import gtk
    
    clipboard = gtk.clipboard_get()
    
    clipboard.set_text('Hello, World')
    clipboard.store()
    

    This works with the Ctrl + V selection for me.