我试图使一个基本的Windows应用程序构建出用户输入的字符串,然后将其添加到剪贴板。如何使用Python将字符串复制到剪贴板?


当前回答

小部件还具有名为.clipboard_get()的方法,该方法返回剪贴板的内容(除非根据剪贴板中的数据类型发生某种错误)。

在这个错误报告中提到了clipboard_get()方法: http://bugs.python.org/issue14777

奇怪的是,在我通常参考的常见(但非官方的)在线TkInter文档源中并没有提到这种方法。

其他回答

import wx

def ctc(text):

    if not wx.TheClipboard.IsOpened():
        wx.TheClipboard.Open()
        data = wx.TextDataObject()
        data.SetText(text)
        wx.TheClipboard.SetData(data)
    wx.TheClipboard.Close()

ctc(text)

我在这里分享的代码片段利用了格式化文本文件的功能:如果您想将复杂的输出复制到剪贴板,该怎么办?(比如一个列中的numpy数组或一个列表)

import subprocess
import os

def cp2clip(clist):

    #create a temporary file
    fi=open("thisTextfileShouldNotExist.txt","w")

    #write in the text file the way you want your data to be
    for m in clist:
        fi.write(m+"\n")

    #close the file
    fi.close()

    #send "clip < file" to the shell
    cmd="clip < thisTextfileShouldNotExist.txt"
    w = subprocess.check_call(cmd,shell=True)

    #delete the temporary text file
    os.remove("thisTextfileShouldNotExist.txt")

    return w

只适用于windows,我猜可以适用于linux或mac。可能有点复杂……

例子:

>>>cp2clip(["ET","phone","home"])
>>>0

在任何文本编辑器中按Ctrl+V:

ET
phone
home

我没有解决办法,只有一个变通办法。

Windows Vista以后有一个内置的命令,称为剪辑,它从命令行获取命令的输出,并将其放入剪贴板。例如:ipconfig | clip。

所以我用os模块做了一个函数,它接受一个字符串,并使用内置的Windows解决方案将它添加到剪贴板。

import os
def addToClipBoard(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)

# Example
addToClipBoard('penny lane')

# Penny Lane is now in your ears, eyes, and clipboard.

然而,正如前面的评论中所指出的,这种方法的一个缺点是echo命令会自动在文本的末尾添加换行符。为了避免这种情况,你可以使用命令的修改版本:

def addToClipBoard(text):
    command = 'echo | set /p nul=' + text.strip() + '| clip'
    os.system(command)

如果您使用的是Windows XP,只需按照从Windows XP Pro的命令提示符直接复制并粘贴到剪贴板中的步骤即可。

最简单的方法是用pyperclip。适用于python 2和3。

要安装这个库,请使用:

pip install pyperclip

使用示例:

import pyperclip

pyperclip.copy("your string")

如果你想获取剪贴板的内容:

clipboard_content = pyperclip.paste()

复制剪贴板的代码片段:

在名为(clipboard.py)的模块中创建包装器Python代码:

import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import Clipboard
def setText(text):
    Clipboard.SetText(text)

def getText():
    return Clipboard.GetText()

然后将上述模块导入到代码中。

import io
import clipboard
code = clipboard.getText()
print code
code = "abcd"
clipboard.setText(code)

我必须赞扬博客文章在IronPython剪贴板访问。