标签归档:clipboard

如何使用Python在Windows上将字符串复制到剪贴板?

问题:如何使用Python在Windows上将字符串复制到剪贴板?

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

I’m trying to make a basic Windows application that builds a string out of user input and then adds it to the clipboard. How do I copy a string to the clipboard using Python?


回答 0

其实,pywin32并且ctypes似乎是这个简单的任务矫枉过正。Tkinter是一个跨平台的GUI框架,默认情况下随Python一起提供,并且具有剪贴板访问方法以及其他很酷的东西。

如果您只需要在系统剪贴板中放置一些文本,则可以这样做:

from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

仅此而已,无需弄乱特定于平台的第三方库。

如果您使用的是Python 3,请替换TKintertkinter

Actually, pywin32 and ctypes seem to be an overkill for this simple task. Tkinter is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.

If all you need is to put some text to system clipboard, this will do it:

from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

And that’s all, no need to mess around with platform-specific third-party libraries.

If you are using Python 3, replace TKinter with tkinter.


回答 1

我没有解决方案,只是一种解决方法。

Windows Vista及更高版本具有一个内置命令clip,该命令从命令行获取命令的输出并将其放入剪贴板。例如,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的命令提示符直接复制并粘贴到剪贴板中的步骤进行操作

I didn’t have a solution, just a workaround.

Windows Vista onwards has an inbuilt command called clip that takes the output of a command from command line and puts it into the clipboard. For example, ipconfig | clip.

So I made a function with the os module which takes a string and adds it to the clipboard using the inbuilt Windows solution.

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.

As previously noted in the comments however, one downside to this approach is that the echo command automatically adds a newline to the end of your text. To avoid this you can use a modified version of the command:

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

If you are using Windows XP it will work just following the steps in Copy and paste from Windows XP Pro’s command prompt straight to the Clipboard.


回答 2

您还可以使用ctypes进入Windows API并避免使用大量的pywin32软件包。这就是我使用的(不好意思的样式,但是这里有想法):

import ctypes

# Get required functions, strcpy..
strcpy = ctypes.cdll.msvcrt.strcpy
ocb = ctypes.windll.user32.OpenClipboard    # Basic clipboard functions
ecb = ctypes.windll.user32.EmptyClipboard
gcd = ctypes.windll.user32.GetClipboardData
scd = ctypes.windll.user32.SetClipboardData
ccb = ctypes.windll.user32.CloseClipboard
ga = ctypes.windll.kernel32.GlobalAlloc    # Global memory allocation
gl = ctypes.windll.kernel32.GlobalLock     # Global memory Locking
gul = ctypes.windll.kernel32.GlobalUnlock
GMEM_DDESHARE = 0x2000

def Get():
  ocb(None) # Open Clip, Default task

  pcontents = gcd(1) # 1 means CF_TEXT.. too lazy to get the token thingy...

  data = ctypes.c_char_p(pcontents).value

  #gul(pcontents) ?
  ccb()

  return data

def Paste(data):
  ocb(None) # Open Clip, Default task

  ecb()

  hCd = ga(GMEM_DDESHARE, len(bytes(data,"ascii")) + 1)

  pchData = gl(hCd)

  strcpy(ctypes.c_char_p(pchData), bytes(data, "ascii"))

  gul(hCd)

  scd(1, hCd)

  ccb()

You can also use ctypes to tap into the Windows API and avoid the massive pywin32 package. This is what I use (excuse the poor style, but the idea is there):

import ctypes

# Get required functions, strcpy..
strcpy = ctypes.cdll.msvcrt.strcpy
ocb = ctypes.windll.user32.OpenClipboard    # Basic clipboard functions
ecb = ctypes.windll.user32.EmptyClipboard
gcd = ctypes.windll.user32.GetClipboardData
scd = ctypes.windll.user32.SetClipboardData
ccb = ctypes.windll.user32.CloseClipboard
ga = ctypes.windll.kernel32.GlobalAlloc    # Global memory allocation
gl = ctypes.windll.kernel32.GlobalLock     # Global memory Locking
gul = ctypes.windll.kernel32.GlobalUnlock
GMEM_DDESHARE = 0x2000

def Get():
  ocb(None) # Open Clip, Default task

  pcontents = gcd(1) # 1 means CF_TEXT.. too lazy to get the token thingy...

  data = ctypes.c_char_p(pcontents).value

  #gul(pcontents) ?
  ccb()

  return data

def Paste(data):
  ocb(None) # Open Clip, Default task

  ecb()

  hCd = ga(GMEM_DDESHARE, len(bytes(data,"ascii")) + 1)

  pchData = gl(hCd)

  strcpy(ctypes.c_char_p(pchData), bytes(data, "ascii"))

  gul(hCd)

  scd(1, hCd)

  ccb()

回答 3

您可以使用pyperclip-跨平台剪贴板模块。或Xerox-类似的模块,但需要win32 Python模块才能在Windows上运行。

You can use pyperclip – cross-platform clipboard module. Or Xerox – similar module, except requires the win32 Python module to work on Windows.


回答 4

您可以使用出色的熊猫,它具有内置的剪贴板支持,但是您需要通过DataFrame。

import pandas as pd
df=pd.DataFrame(['Text to copy'])
df.to_clipboard(index=False,header=False)

You can use the excellent pandas, which has a built in clipboard support, but you need to pass through a DataFrame.

import pandas as pd
df=pd.DataFrame(['Text to copy'])
df.to_clipboard(index=False,header=False)

回答 5

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

要安装此库,请使用:

pip install pyperclip

用法示例:

import pyperclip

pyperclip.copy("your string")

如果要获取剪贴板的内容:

clipboard_content = pyperclip.paste()

The simplest way is with pyperclip. Works in python 2 and 3.

To install this library, use:

pip install pyperclip

Example usage:

import pyperclip

pyperclip.copy("your string")

If you want to get the contents of the clipboard:

clipboard_content = pyperclip.paste()

回答 6

我尝试了各种解决方案,但这是通过我的测试的最简单的解决方案:

#coding=utf-8

import win32clipboard  # http://sourceforge.net/projects/pywin32/

def copy(text):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT)
    win32clipboard.CloseClipboard()
def paste():
    win32clipboard.OpenClipboard()
    data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
    win32clipboard.CloseClipboard()
    return data

if __name__ == "__main__":  
    text = "Testing\nthe “clip—board”: 📋"
    try: text = text.decode('utf8')  # Python 2 needs decode to make a Unicode string.
    except AttributeError: pass
    print("%r" % text.encode('utf8'))
    copy(text)
    data = paste()
    print("%r" % data.encode('utf8'))
    print("OK" if text == data else "FAIL")

    try: print(data)
    except UnicodeEncodeError as er:
        print(er)
        print(data.encode('utf8'))

在Windows 8.1上的Python 3.4和Windows 7上的Python 2.7中都经过了测试,还可以使用从Windows复制的Unix换行符读取Unicode数据。Python退出后,复制的数据将保留在剪贴板上:"Testing the “clip—board”: 📋"

如果您不希望外部依赖,请使用以下代码(现在是跨平台pyperclip-的一部分C:\Python34\Scripts\pip install --upgrade pyperclip):

def copy(text):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)
    try:  # Python 2
        if not isinstance(text, unicode):
            text = text.decode('mbcs')
    except NameError:
        if not isinstance(text, str):
            text = text.decode('mbcs')
    d.user32.OpenClipboard(0)
    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard()

def paste():
    CF_UNICODETEXT = 13
    d = ctypes.windll
    d.user32.OpenClipboard(0)
    handle = d.user32.GetClipboardData(CF_UNICODETEXT)
    text = ctypes.c_wchar_p(handle).value
    d.user32.CloseClipboard()
    return text

I’ve tried various solutions, but this is the simplest one that passes my test:

#coding=utf-8

import win32clipboard  # http://sourceforge.net/projects/pywin32/

def copy(text):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT)
    win32clipboard.CloseClipboard()
def paste():
    win32clipboard.OpenClipboard()
    data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
    win32clipboard.CloseClipboard()
    return data

if __name__ == "__main__":  
    text = "Testing\nthe “clip—board”: 📋"
    try: text = text.decode('utf8')  # Python 2 needs decode to make a Unicode string.
    except AttributeError: pass
    print("%r" % text.encode('utf8'))
    copy(text)
    data = paste()
    print("%r" % data.encode('utf8'))
    print("OK" if text == data else "FAIL")

    try: print(data)
    except UnicodeEncodeError as er:
        print(er)
        print(data.encode('utf8'))

Tested OK in Python 3.4 on Windows 8.1 and Python 2.7 on Windows 7. Also when reading Unicode data with Unix linefeeds copied from Windows. Copied data stays on the clipboard after Python exits: "Testing the “clip—board”: 📋"

If you want no external dependencies, use this code (now part of cross-platform pyperclipC:\Python34\Scripts\pip install --upgrade pyperclip):

def copy(text):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)
    try:  # Python 2
        if not isinstance(text, unicode):
            text = text.decode('mbcs')
    except NameError:
        if not isinstance(text, str):
            text = text.decode('mbcs')
    d.user32.OpenClipboard(0)
    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard()

def paste():
    CF_UNICODETEXT = 13
    d = ctypes.windll
    d.user32.OpenClipboard(0)
    handle = d.user32.GetClipboardData(CF_UNICODETEXT)
    text = ctypes.c_wchar_p(handle).value
    d.user32.CloseClipboard()
    return text

回答 7

由于某些原因,我一直无法获得Tk解决方案来为我工作。kapace的解决方案更可行,但是格式与我的风格相反,并且不适用于Unicode。这是修改后的版本。

import ctypes

OpenClipboard = ctypes.windll.user32.OpenClipboard
EmptyClipboard = ctypes.windll.user32.EmptyClipboard
GetClipboardData = ctypes.windll.user32.GetClipboardData
SetClipboardData = ctypes.windll.user32.SetClipboardData
CloseClipboard = ctypes.windll.user32.CloseClipboard
CF_UNICODETEXT = 13

GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc
GlobalLock = ctypes.windll.kernel32.GlobalLock
GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock
GlobalSize = ctypes.windll.kernel32.GlobalSize
GMEM_MOVEABLE = 0x0002
GMEM_ZEROINIT = 0x0040

unicode_type = type(u'')

def get():
    text = None
    OpenClipboard(None)
    handle = GetClipboardData(CF_UNICODETEXT)
    pcontents = GlobalLock(handle)
    size = GlobalSize(handle)
    if pcontents and size:
        raw_data = ctypes.create_string_buffer(size)
        ctypes.memmove(raw_data, pcontents, size)
        text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
    GlobalUnlock(handle)
    CloseClipboard()
    return text

def put(s):
    if not isinstance(s, unicode_type):
        s = s.decode('mbcs')
    data = s.encode('utf-16le')
    OpenClipboard(None)
    EmptyClipboard()
    handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2)
    pcontents = GlobalLock(handle)
    ctypes.memmove(pcontents, data, len(data))
    GlobalUnlock(handle)
    SetClipboardData(CF_UNICODETEXT, handle)
    CloseClipboard()

paste = get
copy = put

自从首次创建此答案以来,上述内容已经发生了变化,以便更好地应对扩展的Unicode字符和Python3。它已经在Python 2.7和3.5中进行了测试,甚至可以与表情符号一起使用\U0001f601 (😁)

For some reason I’ve never been able to get the Tk solution to work for me. kapace’s solution is much more workable, but the formatting is contrary to my style and it doesn’t work with Unicode. Here’s a modified version.

import ctypes

OpenClipboard = ctypes.windll.user32.OpenClipboard
EmptyClipboard = ctypes.windll.user32.EmptyClipboard
GetClipboardData = ctypes.windll.user32.GetClipboardData
SetClipboardData = ctypes.windll.user32.SetClipboardData
CloseClipboard = ctypes.windll.user32.CloseClipboard
CF_UNICODETEXT = 13

GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc
GlobalLock = ctypes.windll.kernel32.GlobalLock
GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock
GlobalSize = ctypes.windll.kernel32.GlobalSize
GMEM_MOVEABLE = 0x0002
GMEM_ZEROINIT = 0x0040

unicode_type = type(u'')

def get():
    text = None
    OpenClipboard(None)
    handle = GetClipboardData(CF_UNICODETEXT)
    pcontents = GlobalLock(handle)
    size = GlobalSize(handle)
    if pcontents and size:
        raw_data = ctypes.create_string_buffer(size)
        ctypes.memmove(raw_data, pcontents, size)
        text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
    GlobalUnlock(handle)
    CloseClipboard()
    return text

def put(s):
    if not isinstance(s, unicode_type):
        s = s.decode('mbcs')
    data = s.encode('utf-16le')
    OpenClipboard(None)
    EmptyClipboard()
    handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2)
    pcontents = GlobalLock(handle)
    ctypes.memmove(pcontents, data, len(data))
    GlobalUnlock(handle)
    SetClipboardData(CF_UNICODETEXT, handle)
    CloseClipboard()

paste = get
copy = put

The above has changed since this answer was first created, to better cope with extended Unicode characters and Python 3. It has been tested in both Python 2.7 and 3.5, and works even with emoji such as \U0001f601 (😁).


回答 8

看来您需要将win32clipboard添加到您的站点包中。它是pywin32软件包的一部分

Looks like you need to add win32clipboard to your site-packages. It’s part of the pywin32 package


回答 9

您可以使用module clipboard。它简单易用。适用于MacWindowsLinux
注意:它的替代pyperclip

安装后,将其导入:

import clipboard

然后,您可以像这样复制:

clipboard.copy("This is copied")

您还可以粘贴复制的文本:

clipboard.paste()

You can use module clipboard. Its simple and extremely easy to use. Works with Mac, Windows, & Linux.
Note: Its an alternative of pyperclip

After installing, import it:

import clipboard

Then you can copy like this:

clipboard.copy("This is copied")

You can also paste the copied text:

clipboard.paste()

回答 10

这是我找到的最简单,最可靠的方法,如果您还可以,取决于熊猫。但是,我认为这并不是Pandas API的正式组成部分,因此它可能会在将来的更新中失效。从0.25.3开始

from pandas.io.clipboard import copy 
copy("test")

Here’s the most easy and reliable way I found if you’re okay depending on Pandas. However I don’t think this is officially part of the Pandas API so it may break with future updates. It works as of 0.25.3

from pandas.io import clipboard
clipboard.copy("test")

回答 11

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

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

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

Widgets also have method named .clipboard_get() that returns the contents of the clipboard (unless some kind of error happens based on the type of data in the clipboard).

The clipboard_get() method is mentioned in this bug report:
http://bugs.python.org/issue14777

Strangely, this method was not mentioned in the common (but unofficial) online TkInter documentation sources that I usually refer to.


回答 12

我认为有一个更简单的解决方案。

name = input('What is your name? ')
print('Hello %s' % (name) )

然后在命令行中运行程序

python greeter.py | 夹

这会将文件的输出通过管道传输到剪贴板

I think there is a much simpler solution to this.

name = input('What is your name? ')
print('Hello %s' % (name) )

Then run your program in the command line

python greeter.py | clip

This will pipe the output of your file to the clipboard


回答 13

除了Mark Ransom使用ctypes 的答案之外:这不适用于(所有?)x64系统,因为句柄似乎被截断为int大小。显式定义args和返回值有助于克服此问题。

import ctypes
import ctypes.wintypes as w

CF_UNICODETEXT = 13

u32 = ctypes.WinDLL('user32')
k32 = ctypes.WinDLL('kernel32')

OpenClipboard = u32.OpenClipboard
OpenClipboard.argtypes = w.HWND,
OpenClipboard.restype = w.BOOL

GetClipboardData = u32.GetClipboardData
GetClipboardData.argtypes = w.UINT,
GetClipboardData.restype = w.HANDLE

EmptyClipboard = u32.EmptyClipboard
EmptyClipboard.restype = w.BOOL

SetClipboardData = u32.SetClipboardData
SetClipboardData.argtypes = w.UINT, w.HANDLE,
SetClipboardData.restype = w.HANDLE

CloseClipboard = u32.CloseClipboard
CloseClipboard.argtypes = None
CloseClipboard.restype = w.BOOL

GHND = 0x0042

GlobalAlloc = k32.GlobalAlloc
GlobalAlloc.argtypes = w.UINT, w.ctypes.c_size_t,
GlobalAlloc.restype = w.HGLOBAL

GlobalLock = k32.GlobalLock
GlobalLock.argtypes = w.HGLOBAL,
GlobalLock.restype = w.LPVOID

GlobalUnlock = k32.GlobalUnlock
GlobalUnlock.argtypes = w.HGLOBAL,
GlobalUnlock.restype = w.BOOL

GlobalSize = k32.GlobalSize
GlobalSize.argtypes = w.HGLOBAL,
GlobalSize.restype = w.ctypes.c_size_t

unicode_type = type(u'')

def get():
    text = None
    OpenClipboard(None)
    handle = GetClipboardData(CF_UNICODETEXT)
    pcontents = GlobalLock(handle)
    size = GlobalSize(handle)
    if pcontents and size:
        raw_data = ctypes.create_string_buffer(size)
        ctypes.memmove(raw_data, pcontents, size)
        text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
    GlobalUnlock(handle)
    CloseClipboard()
    return text

def put(s):
    if not isinstance(s, unicode_type):
        s = s.decode('mbcs')
    data = s.encode('utf-16le')
    OpenClipboard(None)
    EmptyClipboard()
    handle = GlobalAlloc(GHND, len(data) + 2)
    pcontents = GlobalLock(handle)
    ctypes.memmove(pcontents, data, len(data))
    GlobalUnlock(handle)
    SetClipboardData(CF_UNICODETEXT, handle)
    CloseClipboard()

#Test run
paste = get
copy = put
copy("Hello World!")
print(paste())

In addition to Mark Ransom’s answer using ctypes: This does not work for (all?) x64 systems since the handles seem to be truncated to int-size. Explicitly defining args and return values helps to overcomes this problem.

import ctypes
import ctypes.wintypes as w

CF_UNICODETEXT = 13

u32 = ctypes.WinDLL('user32')
k32 = ctypes.WinDLL('kernel32')

OpenClipboard = u32.OpenClipboard
OpenClipboard.argtypes = w.HWND,
OpenClipboard.restype = w.BOOL

GetClipboardData = u32.GetClipboardData
GetClipboardData.argtypes = w.UINT,
GetClipboardData.restype = w.HANDLE

EmptyClipboard = u32.EmptyClipboard
EmptyClipboard.restype = w.BOOL

SetClipboardData = u32.SetClipboardData
SetClipboardData.argtypes = w.UINT, w.HANDLE,
SetClipboardData.restype = w.HANDLE

CloseClipboard = u32.CloseClipboard
CloseClipboard.argtypes = None
CloseClipboard.restype = w.BOOL

GHND = 0x0042

GlobalAlloc = k32.GlobalAlloc
GlobalAlloc.argtypes = w.UINT, w.ctypes.c_size_t,
GlobalAlloc.restype = w.HGLOBAL

GlobalLock = k32.GlobalLock
GlobalLock.argtypes = w.HGLOBAL,
GlobalLock.restype = w.LPVOID

GlobalUnlock = k32.GlobalUnlock
GlobalUnlock.argtypes = w.HGLOBAL,
GlobalUnlock.restype = w.BOOL

GlobalSize = k32.GlobalSize
GlobalSize.argtypes = w.HGLOBAL,
GlobalSize.restype = w.ctypes.c_size_t

unicode_type = type(u'')

def get():
    text = None
    OpenClipboard(None)
    handle = GetClipboardData(CF_UNICODETEXT)
    pcontents = GlobalLock(handle)
    size = GlobalSize(handle)
    if pcontents and size:
        raw_data = ctypes.create_string_buffer(size)
        ctypes.memmove(raw_data, pcontents, size)
        text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
    GlobalUnlock(handle)
    CloseClipboard()
    return text

def put(s):
    if not isinstance(s, unicode_type):
        s = s.decode('mbcs')
    data = s.encode('utf-16le')
    OpenClipboard(None)
    EmptyClipboard()
    handle = GlobalAlloc(GHND, len(data) + 2)
    pcontents = GlobalLock(handle)
    ctypes.memmove(pcontents, data, len(data))
    GlobalUnlock(handle)
    SetClipboardData(CF_UNICODETEXT, handle)
    CloseClipboard()

#Test run
paste = get
copy = put
copy("Hello World!")
print(paste())

回答 14

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

回答 15

我在这里共享的代码片段利用了格式化文本文件的功能:如果要将复杂的输出复制到剪贴板怎么办?(在列或某物列表中说一个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

The snippet I share here take advantage of the ability to format text files: what if you want to copy a complex output to the clipboard ? (Say a numpy array in column or a list of something)

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

works only for windows, can be adapted for linux or mac I guess. Maybe a bit complicated…

example:

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

Ctrl+V in any text editor :

ET
phone
home

回答 16

这是雾化器的改进答案。

注意2呼叫update()200 ms它们之间的延迟。它们由于剪贴板的不稳定状态而保护冻结的应用程序:

from Tkinter import Tk
import time     

r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('some string')

r.update()
time.sleep(.2)
r.update()

r.destroy()

This is the improved answer of atomizer.

Note 2 calls of update() and 200 ms delay between them. They protect freezing applications due to an unstable state of the clipboard:

from Tkinter import Tk
import time     

r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('some string')

r.update()
time.sleep(.2)
r.update()

r.destroy()

回答 17

使用python的剪贴板库!

import clipboard as cp
cp.copy("abc")

剪贴板现在包含“ abc”。粘贴愉快!

Use python’s clipboard library!

import clipboard as cp
cp.copy("abc")

Clipboard contains ‘abc’ now. Happy pasting!


回答 18

并非所有答案都适用于我的各种python配置,因此此解决方案仅使用subprocess模块​​。但是,copy_keyword必须是pbcopyMac或clipWindows:

import subprocess
subprocess.run('copy_keyword', universal_newlines=True, input='New Clipboard Value 😀')

以下是一些更广泛的代码,它们可以自动检查当前操作系统是什么:

import platform
import subprocess

copy_string = 'New Clipboard Value 😀'

# Check which operating system is running to get the correct copying keyword.
if platform.system() == 'Darwin':
    copy_keyword = 'pbcopy'
elif platform.system() == 'Windows':
    copy_keyword = 'clip'

subprocess.run(copy_keyword, universal_newlines=True, input=copy_string)

Not all of the answers worked for my various python configurations so this solution only uses the subprocess module. However, copy_keyword has to be pbcopy for Mac or clip for Windows:

import subprocess
subprocess.run('copy_keyword', universal_newlines=True, input='New Clipboard Value 😀')

Here’s some more extensive code that automatically checks what the current operating system is:

import platform
import subprocess

copy_string = 'New Clipboard Value 😀'

# Check which operating system is running to get the correct copying keyword.
if platform.system() == 'Darwin':
    copy_keyword = 'pbcopy'
elif platform.system() == 'Windows':
    copy_keyword = 'clip'

subprocess.run(copy_keyword, universal_newlines=True, input=copy_string)

回答 19

您可以使用winclip32模块!安装:

pip install winclip32

复制:

import winclip32
winclip32.set_clipboard_data(winclip32.UNICODE_STD_TEXT, "some text")

要得到:

import winclip32
print(winclip32.get_clipboard_data(winclip32.UNICODE_STD_TEXT))

有关更多信息:https : //pypi.org/project/winclip32/

You can use winclip32 module! install:

pip install winclip32

to copy:

import winclip32
winclip32.set_clipboard_data(winclip32.UNICODE_STD_TEXT, "some text")

to get:

import winclip32
print(winclip32.get_clipboard_data(winclip32.UNICODE_STD_TEXT))

for more informations: https://pypi.org/project/winclip32/


回答 20

复制剪贴板的代码段:

在名为(剪贴板.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中的博客文章Clipboard Access

Code snippet to copy the clipboard:

Create a wrapper Python code in a module named (clipboard.py):

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

def getText():
    return Clipboard.GetText()

Then import the above module into your code.

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

I must give credit to the blog post Clipboard Access in IronPython.


回答 21

您可以尝试以下方法:

command = 'echo content |clip'
subprocess.check_call(command, shell=True)

you can try this:

command = 'echo content |clip'
subprocess.check_call(command, shell=True)

回答 22

from Tkinter import Tk
clip = Tk()
from Tkinter import Tk
clip = Tk()