Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

linux - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...