I have a python script where I want to place a string in the computer's clipboard. I have this working in Linux, Mac, and previously in Windows using cygwin. I had to modify one line of code to get it working in the respective systems. I can't get a string copied to the clipboard on Windows 10's native Linux subsystem. The line below causes error: sh: 1: cannot create /dev/clipboard: Permission denied. Any idea how to modify this line?
os.system("echo hello world > /dev/clipboard")
To get the clipboard contents on Windows you can use win32clipboard
:
import win32clipboard
win32clipboard.OpenClipboard()
cb = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
To set the clipboard:
win32clipboard.OpenClipboard()
# win32clipboard.EmptyClipboard() # uncomment to clear the cb before appending to it
win32clipboard.SetClipboardText("some text")
win32clipboard.CloseClipboard()
If you need a portable approach, you can use Tkinter
, i.e.:
from Tkinter import Tk
r = Tk()
r.withdraw()
# r.clipboard_clear() # uncomment to clear the cb before appending to it
# set clipboard
r.clipboard_append('add to clipboard')
# get clipboard
result = r.selection_get(selection = "CLIPBOARD")
r.destroy()
Both solutions proved to be working on Windows 10. The last one should work on Mac, Linux and Windows.