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 Pytho
You can use pyperclip - cross-platform clipboard module. Or Xerox - similar module, except requires the win32 Python module to work on Windows.
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()
from Tkinter import Tk
clip = Tk()
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
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
.
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()