Windows 10 Subsystem for Linux - Python - String to computer clipboard
I have a python script where I want to put a string on the clipboard. I have this working on Linux, Mac and earlier on Windows using cygwin. I had to change one line of code to get it to work on the respective systems. I cannot get the line copied to the clipboard in Linux subsystem under Windows 10. The line below throws an error: sh: 1: Unable to create / dev / clipboard: Permission denied. Any idea how to change this line?
os.system("echo hello world > /dev/clipboard")
source to share
To get the contents of the clipboard 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 want a portable approach you can use Tkinter
, that is:
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 turned out to work on Windows 10. The latter should work on Mac, Linux and Windows.
source to share