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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…