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
.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With