Copy Data from the Clipboard on Linux, MAC and Windows with a Single Python Script

Copy data from the clipboard on Linux, Mac and Windows with a single Python script

You could use a GUI toolkit such as Qt to get a portable clipboard API. That said it might be a little overkill to use a whole GUI toolkit just for this. (Unless, of course, you're also going to use it to make a GUI.)

That said, clipboard APIs dealing with plain text should be reasonably simple to make your own abstraction over.

For instance, on OS X you can use PyObjC (which is installed along with OS X) to get plain-text contents of a clipboard:

from AppKit import NSPasteboard
from LaunchServices import
pb = NSPasteboard.generalPasteboard()
text = pb.stringForType_(kUTTypeUTF8PlainText)

CPU architectures

A 32-bit native app on a 64-bit OS will be accessing the same clipboard as a 64-bit one. If you need to support both architectures of an OS, and aren't writing a driver, for Windows it's okay to ship a 32-bit binary; for Linux you'll likely have to do both versions; for OS X, it should be reasonably safe to ship a 64-bit version, all Macs since mid-2007 have had 64-bit CPUs and the OS support is there since Leopard. A Python script will, on Linux, probably be executed by a Python installation from the distribution package manager, whose bitness will match the system, so you don't necessarily need to worry about that.

Store files in clipboard in python (cross-platform)

There are a lot of python modules to do this. One of them is https://pypi.org/project/pyperclip/

The c program in this way is not needed you can read the file in python as text or do all logic that you want and put it in the clipboard.

For full file copy you can use this snippet :

from PyQt4 import QtCore, QtGui

app = QtGui.QApplication([])

data = QtCore.QMimeData()
url = QtCore.QUrl.fromLocalFile('c:\\foo.file')
data.setUrls([url])

app.clipboard().setMimeData(data)

How do I copy a string to the clipboard?

Actually, pywin32 and ctypes seem to be an overkill for this simple task. Tkinter is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.

If all you need is to put some text to system clipboard, this will do it:

from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

And that's all, no need to mess around with platform-specific third-party libraries.

If you are using Python 3, replace TKinter with tkinter.

How do I read text from the clipboard?

You can use the module called win32clipboard, which is part of pywin32.

Here is an example that first sets the clipboard data then gets it:

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

An important reminder from the documentation:

When the window has finished examining or changing the clipboard,
close the clipboard by calling CloseClipboard. This enables other
windows to access the clipboard. Do not place an object on the
clipboard after calling CloseClipboard.

copy clipboard of linux into windows clip-board in network

There is a free, cross-platform, open-source program called Synergy that does exactly what you are describing (and more), and I have tested it with a Windows/Linux connection. You could take a look at the source code and see how the clipboard functions are implemented, or it might fit your needs already.

Is there a way to directly send a python output to clipboard?

You can use an external program, xsel:

from subprocess import Popen, PIPE
p = Popen(['xsel','-pi'], stdin=PIPE)
p.communicate(input='Hello, World')

With xsel, you can set the clipboard you want to work on.

  • -p works with the PRIMARY selection. That's the middle click one.
  • -s works with the SECONDARY selection. I don't know if this is used anymore.
  • -b works with the CLIPBOARD selection. That's your Ctrl + V one.

Read more about X's clipboards here and here.

A quick and dirty function I created to handle this:

def paste(str, p=True, c=True):
from subprocess import Popen, PIPE

if p:
p = Popen(['xsel', '-pi'], stdin=PIPE)
p.communicate(input=str)
if c:
p = Popen(['xsel', '-bi'], stdin=PIPE)
p.communicate(input=str)

paste('Hello', False) # pastes to CLIPBOARD only
paste('Hello', c=False) # pastes to PRIMARY only
paste('Hello') # pastes to both

You can also try pyGTK's clipboard :

import pygtk
pygtk.require('2.0')
import gtk

clipboard = gtk.clipboard_get()

clipboard.set_text('Hello, World')
clipboard.store()

This works with the Ctrl + V selection for me.

Windows 10 Linux subsystem - Python - String to computer clipboard

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.

Python - Getting and setting clipboard data with subprocesses

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.



Related Topics



Leave a reply



Submit