clipboard.py
72 lines
| 2.2 KiB
| text/x-python
|
PythonLexer
|
r1841 | """ Utilities for accessing the platform's clipboard. | ||
""" | ||||
import subprocess | ||||
|
r2205 | from IPython.core.error import TryNext | ||
|
r8308 | import IPython.utils.py3compat as py3compat | ||
|
r1841 | |||
|
r13426 | class ClipboardEmpty(ValueError): | ||
pass | ||||
|
r1841 | def win32_clipboard_get(): | ||
""" Get the current clipboard's text on Windows. | ||||
Requires Mark Hammond's pywin32 extensions. | ||||
""" | ||||
try: | ||||
import win32clipboard | ||||
except ImportError: | ||||
|
r7334 | raise TryNext("Getting text from the clipboard requires the pywin32 " | ||
"extensions: http://sourceforge.net/projects/pywin32/") | ||||
|
r4872 | win32clipboard.OpenClipboard() | ||
|
r13426 | try: | ||
text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) | ||||
|
r16784 | except (TypeError, win32clipboard.error): | ||
|
r13426 | try: | ||
text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT) | ||||
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) | ||||
|
r16784 | except (TypeError, win32clipboard.error): | ||
|
r13426 | raise ClipboardEmpty | ||
finally: | ||||
win32clipboard.CloseClipboard() | ||||
|
r1841 | return text | ||
def osx_clipboard_get(): | ||||
""" Get the clipboard's text on OS X. | ||||
""" | ||||
p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], | ||||
stdout=subprocess.PIPE) | ||||
text, stderr = p.communicate() | ||||
# Text comes in with old Mac \r line endings. Change them to \n. | ||||
|
r8817 | text = text.replace(b'\r', b'\n') | ||
|
r8305 | text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) | ||
|
r1841 | return text | ||
def tkinter_clipboard_get(): | ||||
""" Get the clipboard's text using Tkinter. | ||||
This is the default on systems that are not Windows or OS X. It may | ||||
interfere with other UI toolkits and should be replaced with an | ||||
implementation that uses that toolkit. | ||||
""" | ||||
try: | ||||
|
r13426 | from tkinter import Tk, TclError # Py 3 | ||
|
r1841 | except ImportError: | ||
|
r13354 | try: | ||
|
r13426 | from Tkinter import Tk, TclError # Py 2 | ||
|
r13354 | except ImportError: | ||
raise TryNext("Getting text from the clipboard on this platform " | ||||
"requires Tkinter.") | ||||
root = Tk() | ||||
|
r1841 | root.withdraw() | ||
|
r13426 | try: | ||
text = root.clipboard_get() | ||||
except TclError: | ||||
raise ClipboardEmpty | ||||
finally: | ||||
root.destroy() | ||||
|
r8305 | text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) | ||
|
r1841 | return text | ||