How do I copy a string to the clipboard?

Posted on

Solving problem is about exposing yourself to as many situations as possible like How do I copy a string to the clipboard? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How do I copy a string to the clipboard?, which can be followed any time. Take easy to follow this discuss.

How do I copy a string to the clipboard?

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?

Asked By: tester


Answer #1:

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.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed

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.

Answered By: atomizer

Answer #2:

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'
# 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'

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.

Answered By: user1227883

Answer #3:

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
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) ?
  return data
def Paste(data):
  ocb(None) # Open Clip, Default task
  hCd = ga(GMEM_DDESHARE, len(bytes(data,"ascii")) + 1)
  pchData = gl(hCd)
  strcpy(ctypes.c_char_p(pchData), bytes(data, "ascii"))
  scd(1, hCd)
Answered By: kapace

Answer #4:

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

Answered By: pongo

Answer #5:

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'])
Answered By: Gadi Oron

Answer #6:

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()
Answered By: maviz

Answer #7:

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

import win32clipboard  #
def copy(text):
    win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT)
def paste():
    data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
    return data
if __name__ == "__main__":
    text = "Testingnthe “clip—board”: ?"
    try: text = text.decode('utf8')  # Python 2 needs decode to make a Unicode string.
    except AttributeError: pass
    print("%r" % text.encode('utf8'))
    data = paste()
    print("%r" % data.encode('utf8'))
    print("OK" if text == data else "FAIL")
    try: print(data)
    except UnicodeEncodeError as er:

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:Python34Scriptspip install --upgrade pyperclip):

def copy(text):
    GMEM_DDESHARE = 0x2000
    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')
    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.user32.SetClipboardData(CF_UNICODETEXT, hCd)
def paste():
    d = ctypes.windll
    handle = d.user32.GetClipboardData(CF_UNICODETEXT)
    text = ctypes.c_wchar_p(handle).value
    return text
Answered By: Cees Timmerman

Answer #8:

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
GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc
GlobalLock = ctypes.windll.kernel32.GlobalLock
GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock
GlobalSize = ctypes.windll.kernel32.GlobalSize
unicode_type = type(u'')
def get():
    text = 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'')
    return text
def put(s):
    if not isinstance(s, unicode_type):
        s = s.decode('mbcs')
    data = s.encode('utf-16le')
    handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2)
    pcontents = GlobalLock(handle)
    ctypes.memmove(pcontents, data, len(data))
    SetClipboardData(CF_UNICODETEXT, handle)
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 (?).

Answered By: Mark Ransom

Leave a Reply

Your email address will not be published. Required fields are marked *