Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows 10 Linux subsystem - Python - String to computer clipboard

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")
like image 469
Sanitycheck9999 Avatar asked Jul 30 '26 12:07

Sanitycheck9999


2 Answers

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.

like image 167
Pedro Lobito Avatar answered Aug 02 '26 02:08

Pedro Lobito


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
like image 21
thesonyman101 Avatar answered Aug 02 '26 02:08

thesonyman101