I recently discovered from this post a way to get and set clipboard data in python via subprocesses, which is exactly what I need for my project.
import subprocess
def getClipboardData():
p = subprocess.Popen(['pbpaste'], stdout=subprocess.PIPE)
retcode = p.wait()
data = p.stdout.read()
return data
def setClipboardData(data):
p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
p.stdin.write(data)
p.stdin.close()
retcode = p.wait()
However it only seems to work on the OS X operating system. How can I recreate this functionality across windows, mac and linux?
UPDATE
Using my original code and the windows solution bigbounty provided, I guess I only need a solution for linux now. Perhaps something utilizing xclip or xsel?
In Python, you can copy text (string) to the clipboard and paste (get) text from the clipboard with pyperclip. You can also monitor the clipboard to get the text when updated. asweigart/pyperclip: Python module for cross-platform clipboard functions.
You can use the module called win32clipboard, which is part of pywin32.
To copy text to the clipboard, pass a string to pyperclip. copy() . To paste the text from the clipboard, call pyperclip. paste() and the text will be returned as a string value.
To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument.
For Linux you could use your original code using the xclip
utility instead of pbpaste
/pbcopy
:
import subprocess
def getClipboardData():
p = subprocess.Popen(['xclip','-selection', 'clipboard', '-o'], stdout=subprocess.PIPE)
retcode = p.wait()
data = p.stdout.read()
return data
def setClipboardData(data):
p = subprocess.Popen(['xclip','-selection','clipboard'], stdin=subprocess.PIPE)
p.stdin.write(data)
p.stdin.close()
retcode = p.wait()
xclip
's parameters:
-selection clipboard
: operates over the clipboard selection (X Window have multiple "clipboards"-o
: read from desired selectionYou should notice that this solution operates over binary data. To storing a string you can use:
setClipboardData('foo'.encode())
And lastly if you are willing to use your program within a shell piping look my question about a issue.
For windows,
import win32clipboard
# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
win32clipboard.CloseClipboard()
# get clipboard data
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print data
Single library across all platforms - http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With