有没有一种方法可以直接将python输出发送到剪贴板? [英] Is there a way to directly send a python output to clipboard?

查看:157
本文介绍了有没有一种方法可以直接将python输出发送到剪贴板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果python脚本将在运行脚本后吐出一个字符串,给出我要立即编辑的新写入文件的路径,那么将其直接发送到系统剪贴板将非常好而不是STDOUT.

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.

推荐答案

您可以使用外部程序

You can use an external program, xsel:

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

使用xsel,您可以设置要使用的剪贴板.

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

  • -pPRIMARY选择一起使用.那是中键单击.
  • -sSECONDARY选择一起使用.我不知道是否再使用了.
  • -bCLIPBOARD选择一起使用.那就是你的Ctrl + V.
  • -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.

此处我创建的一种快速而肮脏的功能来处理此问题:

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


您还可以尝试pyGTK的 clipboard :


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()

这适用于我选择的Ctrl + V.

这篇关于有没有一种方法可以直接将python输出发送到剪贴板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆