Python - Retrieving and Setting Clipboard Data with Subprocesses

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 works on OS X operating system. How can I recreate this functionality on Windows, Mac and Linux?

UPDATE

Using my source code and windows solution suggested by bigbounty I think I only need a linux solution. Perhaps something is using xclip or xsel?

+3


source to share


2 answers


For Linux, you can use your source code using xclip

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

parameters:

  • -selection clipboard

    : working on the choice of the clipboard (X Window has several " clipboards "
  • -o

    : reading from the desired selection


You should notice that this solution works on binary data . To store the string, you can use:

setClipboardData('foo'.encode())

      

And finally, if you want to use your program in a shell see my question about the problem.

+2


source


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

      



One library across all platforms - http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/

0


source







All Articles