|
| 1 | +""" |
| 2 | +Taken from the IPython project http://ipython.org |
| 3 | +
|
| 4 | +Used under the terms of the BSD license |
| 5 | +""" |
| 6 | + |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | + |
| 10 | +def clipboard_get(): |
| 11 | + """ Get text from the clipboard. |
| 12 | + """ |
| 13 | + if sys.platform == 'win32': |
| 14 | + try: |
| 15 | + return win32_clipboard_get() |
| 16 | + except Exception: |
| 17 | + pass |
| 18 | + elif sys.platform == 'darwin': |
| 19 | + try: |
| 20 | + return osx_clipboard_get() |
| 21 | + except Exception: |
| 22 | + pass |
| 23 | + return tkinter_clipboard_get() |
| 24 | + |
| 25 | +def win32_clipboard_get(): |
| 26 | + """ Get the current clipboard's text on Windows. |
| 27 | +
|
| 28 | + Requires Mark Hammond's pywin32 extensions. |
| 29 | + """ |
| 30 | + try: |
| 31 | + import win32clipboard |
| 32 | + except ImportError: |
| 33 | + message = ("Getting text from the clipboard requires the pywin32 " |
| 34 | + "extensions: http://sourceforge.net/projects/pywin32/") |
| 35 | + raise Exception(message) |
| 36 | + win32clipboard.OpenClipboard() |
| 37 | + text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT) |
| 38 | + # FIXME: convert \r\n to \n? |
| 39 | + win32clipboard.CloseClipboard() |
| 40 | + return text |
| 41 | + |
| 42 | +def osx_clipboard_get(): |
| 43 | + """ Get the clipboard's text on OS X. |
| 44 | + """ |
| 45 | + p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], |
| 46 | + stdout=subprocess.PIPE) |
| 47 | + text, stderr = p.communicate() |
| 48 | + # Text comes in with old Mac \r line endings. Change them to \n. |
| 49 | + text = text.replace('\r', '\n') |
| 50 | + return text |
| 51 | + |
| 52 | +def tkinter_clipboard_get(): |
| 53 | + """ Get the clipboard's text using Tkinter. |
| 54 | +
|
| 55 | + This is the default on systems that are not Windows or OS X. It may |
| 56 | + interfere with other UI toolkits and should be replaced with an |
| 57 | + implementation that uses that toolkit. |
| 58 | + """ |
| 59 | + try: |
| 60 | + import Tkinter |
| 61 | + except ImportError: |
| 62 | + message = ("Getting text from the clipboard on this platform " |
| 63 | + "requires Tkinter.") |
| 64 | + raise Exception(message) |
| 65 | + root = Tkinter.Tk() |
| 66 | + root.withdraw() |
| 67 | + text = root.clipboard_get() |
| 68 | + root.destroy() |
| 69 | + return text |
0 commit comments