3

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")
2
  • There is no such thing as /dev/clipboard in linux, that's something that only exists in cygwin. Usually programs like xclip or xsel are used to access the X server clipboard on linux, but I'm relatively sure that won't work on the windows linux subsystem.
    – mata
    Commented May 23, 2017 at 22:21
  • 1
    Do you need a solution for Windows in general, in which case it would be normal to use python.exe built for Windows, or a solution specifically when running Linux python under WSL?
    – Eryk Sun
    Commented May 23, 2017 at 22:34

3 Answers 3

4

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.

1

Here's one lib

**pip install clipboard**


import clipboard
clipboard.copy("abc")  # now the clipboard content will be string "abc"
text = clipboard.paste()  # text will have the content of clipboard
0

There is also the pyperclip library. I use this in a couple of tools and it does a great simple job.

Not the answer you're looking for? Browse other questions tagged or ask your own question.