11

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?

DejaVu_Loop
  • 305
  • 2
  • 10

2 Answers2

10

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 selection

You 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.

mglart
  • 360
  • 3
  • 11
2

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/

bigbounty
  • 16,526
  • 5
  • 37
  • 65