Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 863
nye17 Avatar asked Sep 30 '11 04:09

nye17


People also ask

How do you copy and paste output in Python?

To copy text to the clipboard, pass a string to pyperclip. copy() . To paste the text from the clipboard, call pyperclip. paste() and the text will be returned as a string value.

Can Python access the clipboard?

In Python, you can copy text (string) to the clipboard and paste (get) text from the clipboard with pyperclip. You can also monitor the clipboard to get the text when updated. asweigart/pyperclip: Python module for cross-platform clipboard functions.

How do I copy text to clipboard?

Select the text or graphics you want to copy, and press Ctrl+C. Each selection appears in the Clipboard, with the latest at the top.

How read data from clipboard in Python?

You can use the module called win32clipboard, which is part of pywin32. An important reminder from the documentation: When the window has finished examining or changing the clipboard, close the clipboard by calling CloseClipboard. This enables other windows to access the clipboard.


1 Answers

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.

like image 102
NullUserException Avatar answered Sep 27 '22 19:09

NullUserException