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?
Solution 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.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
.
Solution 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'
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.
Solution 3:
You can use pyperclip - cross-platform clipboard module. Or Xerox - similar module, except requires the win32 Python module to work on Windows.