Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to create a script in Python that will collect data put in the clipboard by the user and preferably save it as a list or in a text file or string/array/variable to work with later on.

This should work on Linux all versions (I would assume Ubuntu), Mac OS all versions and Windows all versions. I am not sure if 32bit and 64bit systems have different ways of accessing the data at the clipboard, if they do I guess it would be safe to make this work for the 32bit versions only so people running the 64bit versions can fall back onto the 32bit version of the OS.

The tricky part, apart from this having to work on the mentioned OS, is that I would like the script to run as long as the user does not stop it and while it runs all the data copied into the clipboard by the user is being copied to a list or in a text file or string/array/variable.

Of course there is a time limit at which the user can input data into the clipboard so I was thinking of having a loop scanning the clipboard every second or every 500 milliseconds, check if the content has changed, and if it has, copy it, otherwise don't copy it.

Is there a unified way or module that does this on all different OS or would it be better to write separate scripts for this task for the various OS?

The thing is, this is part of a bigger project that I would like to make work on Linux, Mac and Windows, so having those three options covered and then use Python code that can be used across the mentioned OS for the rest of the script/project would be ideal. Am I asking too much in general from this script concerning it having to work on Linux, Mac and Windows?

like image 733
lowtechsun Avatar asked Dec 17 '22 08:12

lowtechsun


2 Answers

You're probably better off using a more advanced gui toolkit than Tk, but it's in the standard library, so it's available everywhere.

As a really simple example:

import Tkinter
root = Tkinter.Tk()
root.withdraw() # Hide the main window (optional)
text_in_clipboard = root.clipboard_get()
print text_in_clipboard
like image 33
Joe Kington Avatar answered Jan 13 '23 11:01

Joe Kington


The xerox library supports Linux, Mac OS X, and Windows.

Note that it's a very bad idea to perform any action in short (< a minute) intervals, because that makes modern processors wake up regularily. You may want to use the respective operating system's APIs to register a callback once the clipboard changes.

like image 185
phihag Avatar answered Jan 13 '23 11:01

phihag