Advertisement
asweigart

Untitled

Nov 7th, 2017
716
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.76 KB | None | 0 0
  1. """
  2. Pyperclip
  3.  
  4. A cross-platform clipboard module for Python, with copy & paste functions for plain text.
  5. By Al Sweigart al@inventwithpython.com
  6. BSD License
  7.  
  8. Usage:
  9. import pyperclip
  10. pyperclip.copy('The text to be copied to the clipboard.')
  11. spam = pyperclip.paste()
  12.  
  13. if not pyperclip.is_available():
  14. print("Copy functionality unavailable!")
  15.  
  16. On Windows, no additional modules are needed.
  17. On Mac, the pyobjc module is used, falling back to the pbcopy and pbpaste cli
  18. commands. (These commands should come with OS X.).
  19. On Linux, install xclip or xsel via package manager. For example, in Debian:
  20. sudo apt-get install xclip
  21. sudo apt-get install xsel
  22.  
  23. Otherwise on Linux, you will need the gtk or PyQt5/PyQt4 modules installed.
  24.  
  25. gtk and PyQt4 modules are not available for Python 3,
  26. and this module does not work with PyGObject yet.
  27.  
  28. Note: There seem sto be a way to get gtk on Python 3, according to:
  29. https://askubuntu.com/questions/697397/python3-is-not-supporting-gtk-module
  30.  
  31. Cygwin is currently not supported.
  32.  
  33. Security Note: This module runs programs with these names:
  34. - which
  35. - where
  36. - pbcopy
  37. - pbpaste
  38. - xclip
  39. - xsel
  40. - klipper
  41. - qdbus
  42. A malicious user could rename or add programs with these names, tricking
  43. Pyperclip into running them with whatever permissions the Python process has.
  44.  
  45. """
  46. __version__ = '1.6.0'
  47.  
  48. import contextlib
  49. import ctypes
  50. import os
  51. import platform
  52. import subprocess
  53. import sys
  54. import time
  55. import warnings
  56.  
  57. from ctypes import c_size_t, sizeof, c_wchar_p, get_errno, c_wchar
  58.  
  59.  
  60. # `import PyQt4` sys.exit()s if DISPLAY is not in the environment.
  61. # Thus, we need to detect the presence of $DISPLAY manually
  62. # and not load PyQt4 if it is absent.
  63. HAS_DISPLAY = os.getenv("DISPLAY", False)
  64.  
  65. EXCEPT_MSG = """
  66. Pyperclip could not find a copy/paste mechanism for your system.
  67. For more information, please visit https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error """
  68.  
  69. PY2 = sys.version_info[0] == 2
  70.  
  71. STR_OR_UNICODE = unicode if PY2 else str
  72.  
  73. ENCODING = 'utf-8'
  74.  
  75. # The "which" unix command finds where a command is.
  76. if platform.system() == 'Windows':
  77. WHICH_CMD = 'where'
  78. else:
  79. WHICH_CMD = 'which'
  80.  
  81. def _executable_exists(name):
  82. return subprocess.call([WHICH_CMD, name],
  83. stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
  84.  
  85.  
  86.  
  87. # Exceptions
  88. class PyperclipException(RuntimeError):
  89. pass
  90.  
  91. class PyperclipWindowsException(PyperclipException):
  92. def __init__(self, message):
  93. message += " (%s)" % ctypes.WinError()
  94. super(PyperclipWindowsException, self).__init__(message)
  95.  
  96.  
  97.  
  98. def init_osx_pbcopy_clipboard():
  99.  
  100. def copy_osx_pbcopy(text):
  101. p = subprocess.Popen(['pbcopy', 'w'],
  102. stdin=subprocess.PIPE, close_fds=True)
  103. p.communicate(input=text.encode(ENCODING))
  104.  
  105. def paste_osx_pbcopy():
  106. p = subprocess.Popen(['pbpaste', 'r'],
  107. stdout=subprocess.PIPE, close_fds=True)
  108. stdout, stderr = p.communicate()
  109. return stdout.decode(ENCODING)
  110.  
  111. return copy_osx_pbcopy, paste_osx_pbcopy
  112.  
  113.  
  114. def init_osx_pyobjc_clipboard():
  115. def copy_osx_pyobjc(text):
  116. '''Copy string argument to clipboard'''
  117. newStr = Foundation.NSString.stringWithString_(text).nsstring()
  118. newData = newStr.dataUsingEncoding_(Foundation.NSUTF8StringEncoding)
  119. board = AppKit.NSPasteboard.generalPasteboard()
  120. board.declareTypes_owner_([AppKit.NSStringPboardType], None)
  121. board.setData_forType_(newData, AppKit.NSStringPboardType)
  122.  
  123. def paste_osx_pyobjc():
  124. "Returns contents of clipboard"
  125. board = AppKit.NSPasteboard.generalPasteboard()
  126. content = board.stringForType_(AppKit.NSStringPboardType)
  127. return content
  128.  
  129. return copy_osx_pyobjc, paste_osx_pyobjc
  130.  
  131.  
  132. def init_gtk_clipboard():
  133. global gtk
  134. import gtk
  135.  
  136. def copy_gtk(text):
  137. global cb
  138. cb = gtk.Clipboard()
  139. cb.set_text(text)
  140. cb.store()
  141.  
  142. def paste_gtk():
  143. clipboardContents = gtk.Clipboard().wait_for_text()
  144. # for python 2, returns None if the clipboard is blank.
  145. if clipboardContents is None:
  146. return ''
  147. else:
  148. return clipboardContents
  149.  
  150. return copy_gtk, paste_gtk
  151.  
  152.  
  153. def init_qt_clipboard():
  154. global QApplication
  155. # $DISPLAY should exist
  156.  
  157. # Try to import from qtpy, but if that fails try PyQt5 then PyQt4
  158. try:
  159. from qtpy.QtWidgets import QApplication
  160. except:
  161. try:
  162. from PyQt5.QtWidgets import QApplication
  163. except:
  164. from PyQt4.QtGui import QApplication
  165.  
  166. app = QApplication.instance()
  167. if app is None:
  168. app = QApplication([])
  169.  
  170. def copy_qt(text):
  171. cb = app.clipboard()
  172. cb.setText(text)
  173.  
  174. def paste_qt():
  175. cb = app.clipboard()
  176. return STR_OR_UNICODE(cb.text())
  177.  
  178. return copy_qt, paste_qt
  179.  
  180.  
  181. def init_xclip_clipboard():
  182. DEFAULT_SELECTION='c'
  183. PRIMARY_SELECTION='p'
  184.  
  185. def copy_xclip(text, primary=False):
  186. selection=DEFAULT_SELECTION
  187. if primary:
  188. selection=PRIMARY_SELECTION
  189. p = subprocess.Popen(['xclip', '-selection', selection],
  190. stdin=subprocess.PIPE, close_fds=True)
  191. p.communicate(input=text.encode(ENCODING))
  192.  
  193. def paste_xclip(primary=False):
  194. selection=DEFAULT_SELECTION
  195. if primary:
  196. selection=PRIMARY_SELECTION
  197. p = subprocess.Popen(['xclip', '-selection', selection, '-o'],
  198. stdout=subprocess.PIPE,
  199. stderr=subprocess.PIPE,
  200. close_fds=True)
  201. stdout, stderr = p.communicate()
  202. # Intentionally ignore extraneous output on stderr when clipboard is empty
  203. return stdout.decode(ENCODING)
  204.  
  205. return copy_xclip, paste_xclip
  206.  
  207.  
  208. def init_xsel_clipboard():
  209. DEFAULT_SELECTION='-b'
  210. PRIMARY_SELECTION='-p'
  211.  
  212. def copy_xsel(text, primary=False):
  213. selection_flag = DEFAULT_SELECTION
  214. if primary:
  215. selection_flag = PRIMARY_SELECTION
  216. p = subprocess.Popen(['xsel', selection_flag, '-i'],
  217. stdin=subprocess.PIPE, close_fds=True)
  218. p.communicate(input=text.encode(ENCODING))
  219.  
  220. def paste_xsel(primary=False):
  221. selection_flag = DEFAULT_SELECTION
  222. if primary:
  223. selection_flag = PRIMARY_SELECTION
  224. p = subprocess.Popen(['xsel', selection_flag, '-o'],
  225. stdout=subprocess.PIPE, close_fds=True)
  226. stdout, stderr = p.communicate()
  227. return stdout.decode(ENCODING)
  228.  
  229. return copy_xsel, paste_xsel
  230.  
  231.  
  232. def init_klipper_clipboard():
  233. def copy_klipper(text):
  234. p = subprocess.Popen(
  235. ['qdbus', 'org.kde.klipper', '/klipper', 'setClipboardContents',
  236. text.encode(ENCODING)],
  237. stdin=subprocess.PIPE, close_fds=True)
  238. p.communicate(input=None)
  239.  
  240. def paste_klipper():
  241. p = subprocess.Popen(
  242. ['qdbus', 'org.kde.klipper', '/klipper', 'getClipboardContents'],
  243. stdout=subprocess.PIPE, close_fds=True)
  244. stdout, stderr = p.communicate()
  245.  
  246. # Workaround for https://bugs.kde.org/show_bug.cgi?id=342874
  247. # TODO: https://github.com/asweigart/pyperclip/issues/43
  248. clipboardContents = stdout.decode(ENCODING)
  249. # even if blank, Klipper will append a newline at the end
  250. assert len(clipboardContents) > 0
  251. # make sure that newline is there
  252. assert clipboardContents.endswith('\n')
  253. if clipboardContents.endswith('\n'):
  254. clipboardContents = clipboardContents[:-1]
  255. return clipboardContents
  256.  
  257. return copy_klipper, paste_klipper
  258.  
  259.  
  260. def init_dev_clipboard_clipboard():
  261. def copy_dev_clipboard(text):
  262. if text == '':
  263. warnings.warn('Pyperclip cannot copy a blank string to the clipboard on Cygwin. This is effectively a no-op.')
  264. if '\r' in text:
  265. warnings.warn('Pyperclip cannot handle \\r characters on Cygwin.')
  266.  
  267. fo = open('/dev/clipboard', 'wt')
  268. fo.write(text)
  269. fo.close()
  270.  
  271. def paste_dev_clipboard():
  272. fo = open('/dev/clipboard', 'rt')
  273. content = fo.read()
  274. fo.close()
  275. return content
  276.  
  277. return copy_dev_clipboard, paste_dev_clipboard
  278.  
  279.  
  280. def init_no_clipboard():
  281. class ClipboardUnavailable(object):
  282.  
  283. def __call__(self, *args, **kwargs):
  284. raise PyperclipException(EXCEPT_MSG)
  285.  
  286. if PY2:
  287. def __nonzero__(self):
  288. return False
  289. else:
  290. def __bool__(self):
  291. return False
  292.  
  293. return ClipboardUnavailable(), ClipboardUnavailable()
  294.  
  295.  
  296.  
  297.  
  298. # Windows-related clipboard functions:
  299. class CheckedCall(object):
  300. def __init__(self, f):
  301. super(CheckedCall, self).__setattr__("f", f)
  302.  
  303. def __call__(self, *args):
  304. ret = self.f(*args)
  305. if not ret and get_errno():
  306. raise PyperclipWindowsException("Error calling " + self.f.__name__)
  307. return ret
  308.  
  309. def __setattr__(self, key, value):
  310. setattr(self.f, key, value)
  311.  
  312.  
  313. def init_windows_clipboard():
  314. global HGLOBAL, LPVOID, DWORD, LPCSTR, INT, HWND, HINSTANCE, HMENU, BOOL, UINT, HANDLE
  315. from ctypes.wintypes import (HGLOBAL, LPVOID, DWORD, LPCSTR, INT, HWND,
  316. HINSTANCE, HMENU, BOOL, UINT, HANDLE)
  317.  
  318. windll = ctypes.windll
  319. msvcrt = ctypes.CDLL('msvcrt')
  320.  
  321. safeCreateWindowExA = CheckedCall(windll.user32.CreateWindowExA)
  322. safeCreateWindowExA.argtypes = [DWORD, LPCSTR, LPCSTR, DWORD, INT, INT,
  323. INT, INT, HWND, HMENU, HINSTANCE, LPVOID]
  324. safeCreateWindowExA.restype = HWND
  325.  
  326. safeDestroyWindow = CheckedCall(windll.user32.DestroyWindow)
  327. safeDestroyWindow.argtypes = [HWND]
  328. safeDestroyWindow.restype = BOOL
  329.  
  330. OpenClipboard = windll.user32.OpenClipboard
  331. OpenClipboard.argtypes = [HWND]
  332. OpenClipboard.restype = BOOL
  333.  
  334. safeCloseClipboard = CheckedCall(windll.user32.CloseClipboard)
  335. safeCloseClipboard.argtypes = []
  336. safeCloseClipboard.restype = BOOL
  337.  
  338. safeEmptyClipboard = CheckedCall(windll.user32.EmptyClipboard)
  339. safeEmptyClipboard.argtypes = []
  340. safeEmptyClipboard.restype = BOOL
  341.  
  342. safeGetClipboardData = CheckedCall(windll.user32.GetClipboardData)
  343. safeGetClipboardData.argtypes = [UINT]
  344. safeGetClipboardData.restype = HANDLE
  345.  
  346. safeSetClipboardData = CheckedCall(windll.user32.SetClipboardData)
  347. safeSetClipboardData.argtypes = [UINT, HANDLE]
  348. safeSetClipboardData.restype = HANDLE
  349.  
  350. safeGlobalAlloc = CheckedCall(windll.kernel32.GlobalAlloc)
  351. safeGlobalAlloc.argtypes = [UINT, c_size_t]
  352. safeGlobalAlloc.restype = HGLOBAL
  353.  
  354. safeGlobalLock = CheckedCall(windll.kernel32.GlobalLock)
  355. safeGlobalLock.argtypes = [HGLOBAL]
  356. safeGlobalLock.restype = LPVOID
  357.  
  358. safeGlobalUnlock = CheckedCall(windll.kernel32.GlobalUnlock)
  359. safeGlobalUnlock.argtypes = [HGLOBAL]
  360. safeGlobalUnlock.restype = BOOL
  361.  
  362. wcslen = CheckedCall(msvcrt.wcslen)
  363. wcslen.argtypes = [c_wchar_p]
  364. wcslen.restype = UINT
  365.  
  366. GMEM_MOVEABLE = 0x0002
  367. CF_UNICODETEXT = 13
  368.  
  369. @contextlib.contextmanager
  370. def window():
  371. """
  372. Context that provides a valid Windows hwnd.
  373. """
  374. # we really just need the hwnd, so setting "STATIC"
  375. # as predefined lpClass is just fine.
  376. hwnd = safeCreateWindowExA(0, b"STATIC", None, 0, 0, 0, 0, 0,
  377. None, None, None, None)
  378. try:
  379. yield hwnd
  380. finally:
  381. safeDestroyWindow(hwnd)
  382.  
  383. @contextlib.contextmanager
  384. def clipboard(hwnd):
  385. """
  386. Context manager that opens the clipboard and prevents
  387. other applications from modifying the clipboard content.
  388. """
  389. # We may not get the clipboard handle immediately because
  390. # some other application is accessing it (?)
  391. # We try for at least 500ms to get the clipboard.
  392. t = time.time() + 0.5
  393. success = False
  394. while time.time() < t:
  395. success = OpenClipboard(hwnd)
  396. if success:
  397. break
  398. time.sleep(0.01)
  399. if not success:
  400. raise PyperclipWindowsException("Error calling OpenClipboard")
  401.  
  402. try:
  403. yield
  404. finally:
  405. safeCloseClipboard()
  406.  
  407. def copy_windows(text):
  408. # This function is heavily based on
  409. # http://msdn.com/ms649016#_win32_Copying_Information_to_the_Clipboard
  410. with window() as hwnd:
  411. # http://msdn.com/ms649048
  412. # If an application calls OpenClipboard with hwnd set to NULL,
  413. # EmptyClipboard sets the clipboard owner to NULL;
  414. # this causes SetClipboardData to fail.
  415. # => We need a valid hwnd to copy something.
  416. with clipboard(hwnd):
  417. safeEmptyClipboard()
  418.  
  419. if text:
  420. # http://msdn.com/ms649051
  421. # If the hMem parameter identifies a memory object,
  422. # the object must have been allocated using the
  423. # function with the GMEM_MOVEABLE flag.
  424. count = wcslen(text) + 1
  425. handle = safeGlobalAlloc(GMEM_MOVEABLE,
  426. count * sizeof(c_wchar))
  427. locked_handle = safeGlobalLock(handle)
  428.  
  429. ctypes.memmove(c_wchar_p(locked_handle), c_wchar_p(text), count * sizeof(c_wchar))
  430.  
  431. safeGlobalUnlock(handle)
  432. safeSetClipboardData(CF_UNICODETEXT, handle)
  433.  
  434. def paste_windows():
  435. with clipboard(None):
  436. handle = safeGetClipboardData(CF_UNICODETEXT)
  437. if not handle:
  438. # GetClipboardData may return NULL with errno == NO_ERROR
  439. # if the clipboard is empty.
  440. # (Also, it may return a handle to an empty buffer,
  441. # but technically that's not empty)
  442. return ""
  443. return c_wchar_p(handle).value
  444.  
  445. return copy_windows, paste_windows
  446.  
  447.  
  448.  
  449.  
  450. # Automatic detection of clipboard mechanisms and importing is done in deteremine_clipboard():
  451. def determine_clipboard():
  452. '''
  453. Determine the OS/platform and set the copy() and paste() functions
  454. accordingly.
  455. '''
  456.  
  457. global Foundation, AppKit, gtk, qtpy, PyQt4, PyQt5
  458.  
  459. # Setup for the CYGWIN platform:
  460. if 'cygwin' in platform.system().lower(): # Cygwin has a variety of values returned by platform.system(), such as 'CYGWIN_NT-6.1'
  461. # FIXME: pyperclip currently does not support Cygwin,
  462. # see https://github.com/asweigart/pyperclip/issues/55
  463. if os.path.exists('/dev/clipboard'):
  464. warnings.warn('Pyperclip\'s support for Cygwin is not perfect, see https://github.com/asweigart/pyperclip/issues/55')
  465. return init_dev_clipboard_clipboard()
  466.  
  467. # Setup for the WINDOWS platform:
  468. elif os.name == 'nt' or platform.system() == 'Windows':
  469. return init_windows_clipboard()
  470.  
  471. # Setup for the MAC OS X platform:
  472. if os.name == 'mac' or platform.system() == 'Darwin':
  473. try:
  474. import Foundation # check if pyobjc is installed
  475. import AppKit
  476. except ImportError:
  477. return init_osx_pbcopy_clipboard()
  478. else:
  479. return init_osx_pyobjc_clipboard()
  480.  
  481. # Setup for the LINUX platform:
  482. if HAS_DISPLAY:
  483. try:
  484. import gtk # check if gtk is installed
  485. except ImportError:
  486. pass # We want to fail fast for all non-ImportError exceptions.
  487. else:
  488. return init_gtk_clipboard()
  489.  
  490. if _executable_exists("xclip"):
  491. return init_xclip_clipboard()
  492. if _executable_exists("xsel"):
  493. return init_xsel_clipboard()
  494. if _executable_exists("klipper") and _executable_exists("qdbus"):
  495. return init_klipper_clipboard()
  496.  
  497. try:
  498. # qtpy is a small abstraction layer that lets you write applications using a single api call to either PyQt or PySide.
  499. # https://pypi.python.org/pypi/QtPy
  500. import qtpy # check if qtpy is installed
  501. except ImportError:
  502. # If qtpy isn't installed, fall back on importing PyQt4.
  503. try:
  504. import PyQt5 # check if PyQt5 is installed
  505. except ImportError:
  506. try:
  507. import PyQt4 # check if PyQt4 is installed
  508. except ImportError:
  509. pass # We want to fail fast for all non-ImportError exceptions.
  510. else:
  511. return init_qt_clipboard()
  512. else:
  513. return init_qt_clipboard()
  514. else:
  515. return init_qt_clipboard()
  516.  
  517.  
  518. return init_no_clipboard()
  519.  
  520.  
  521. def set_clipboard(clipboard):
  522. '''
  523. Explicitly sets the clipboard mechanism. The "clipboard mechanism" is how
  524. the copy() and paste() functions interact with the operating system to
  525. implement the copy/paste feature. The clipboard parameter must be one of:
  526. - pbcopy
  527. - pbobjc (default on Mac OS X)
  528. - gtk
  529. - qt
  530. - xclip
  531. - xsel
  532. - klipper
  533. - windows (default on Windows)
  534. - no (this is what is set when no clipboard mechanism can be found)
  535. '''
  536. global copy, paste
  537.  
  538. clipboard_types = {'pbcopy': init_osx_pbcopy_clipboard,
  539. 'pyobjc': init_osx_pyobjc_clipboard,
  540. 'gtk': init_gtk_clipboard,
  541. 'qt': init_qt_clipboard, # TODO - split this into 'qtpy', 'pyqt4', and 'pyqt5'
  542. 'xclip': init_xclip_clipboard,
  543. 'xsel': init_xsel_clipboard,
  544. 'klipper': init_klipper_clipboard,
  545. 'windows': init_windows_clipboard,
  546. 'no': init_no_clipboard}
  547.  
  548. if clipboard not in clipboard_types:
  549. raise ValueError('Argument must be one of %s' % (', '.join([repr(_) for _ in clipboard_types.keys()])))
  550.  
  551. # Sets pyperclip's copy() and paste() functions:
  552. copy, paste = clipboard_types[clipboard]()
  553.  
  554.  
  555. def lazy_load_stub_copy(text):
  556. '''
  557. A stub function for copy(), which will load the real copy() function when
  558. called so that the real copy() function is used for later calls.
  559.  
  560. This allows users to import pyperclip without having determine_clipboard()
  561. automatically run, which will automatically select a clipboard mechanism.
  562. This could be a problem if it selects, say, the memory-heavy PyQt4 module
  563. but the user was just going to immediately call set_clipboard() to use a
  564. different clipboard mechanism.
  565.  
  566. The lazy loading this stub function implements gives the user a chance to
  567. call set_clipboard() to pick another clipboard mechanism. Or, if the user
  568. simply calls copy() or paste() without calling set_clipboard() first,
  569. will fall back on whatever clipboard mechanism that determine_clipboard()
  570. automatically chooses.
  571. '''
  572. global copy, paste
  573. copy, paste = determine_clipboard()
  574. return copy(text)
  575.  
  576.  
  577. def lazy_load_stub_paste():
  578. '''
  579. A stub function for paste(), which will load the real paste() function when
  580. called so that the real paste() function is used for later calls.
  581.  
  582. This allows users to import pyperclip without having determine_clipboard()
  583. automatically run, which will automatically select a clipboard mechanism.
  584. This could be a problem if it selects, say, the memory-heavy PyQt4 module
  585. but the user was just going to immediately call set_clipboard() to use a
  586. different clipboard mechanism.
  587.  
  588. The lazy loading this stub function implements gives the user a chance to
  589. call set_clipboard() to pick another clipboard mechanism. Or, if the user
  590. simply calls copy() or paste() without calling set_clipboard() first,
  591. will fall back on whatever clipboard mechanism that determine_clipboard()
  592. automatically chooses.
  593. '''
  594. global copy, paste
  595. copy, paste = determine_clipboard()
  596. return paste()
  597.  
  598.  
  599. def is_available():
  600. return copy != lazy_load_stub_copy and paste != lazy_load_stub_paste
  601.  
  602.  
  603. # Initially, copy() and paste() are set to lazy loading wrappers which will
  604. # set `copy` and `paste` to real functions the first time they're used, unless
  605. # set_clipboard() or determine_clipboard() is called first.
  606. copy, paste = lazy_load_stub_copy, lazy_load_stub_paste
  607.  
  608.  
  609. __all__ = ['copy', 'paste', 'set_clipboard', 'determine_clipboard']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement