././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1758897619.0100121 pyperclip-1.11.0/0000755000076500000240000000000015065522723012127 5ustar00alstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1758156009.0 pyperclip-1.11.0/AUTHORS.txt0000644000076500000240000000447315062652351014023 0ustar00alstaffHere is an inevitably incomplete list of MUCH-APPRECIATED CONTRIBUTORS -- people who have submitted patches, reported bugs, added translations, helped answer newbie questions, and generally made Pyperclip that much better: Al Sweigart Alexander Cobleigh @cblgh Andrea Scarpino https://github.com/ilpianista Aniket Pandey https://github.com/lordaniket06 Anton Yakutovich https://github.com/drakulavich Brian Levin https://github.com/bnice5000 Carvell Scott https://github.com/CarvellScott Cees Timmerman https://github.com/CTimmerman Chris Clark Christopher Lambert https://github.com/XN137 Chris Woerz https://github.com/erendrake Corey Bryant https://github.com/coreycb Daniel Shimon https://github.com/daniel-shimon Edd Barrett https://github.com/vext01 Eugene Yang https://github.com/eugene-yang Felix Yan https://github.com/felixonmars Fredrik Borg https://github.com/frbor fthoma https://github.com/fthoma Greg Witt https://github.com/GoodGuyGregory hinlader https://github.com/hinlader Hugo van Kemenade https://github.com/hugovk Hynek Cernoch https://github.com/hynekcer Jason R. Coombs https://github.com/jaraco Jon Crall https://github.com/Erotemic Jonathan Slenders https://github.com/jonathanslenders JustAShoeMaker https://github.com/JustAShoeMaker Marcelo Glezer https://github.com/gato masajxxx https://github.com/masajxxx Maximilian Hils https://github.com/mhils mgunyho https://github.com/mgunyho Melwyn Francis Carlo https://github.com/melwyncarlo Michał Górny https://github.com/mgorny Nicola Guerrera https://github.com/nik012003 Nikolaos-Digenis Karagiannis https://github.com/Digenis Nils Ohlmeier https://github.com/nils-ohlmeier Orson Peters https://github.com/orlp pgajdos https://github.com/pgajdos PirateOfAndaman https://github.com/PirateOfAndaman Six https://github.com/brbsix Stefan Devai https://github.com/stefandevai Stephen Finucane https://github.com/stephenfin Stefan Scherfke https://github.com/sscherfke Steve Elam Tamir Bahar https://github.com/tmr232 Terrel Shumway https://github.com/lernisto Tim Cuthbertson https://github.com/timbertson Tim Gates https://github.com/timgates42 Todd Leonhardt https://github.com/tleonhardt Troy Sankey https://github.com/pwnage101 utagawa kiki https://github.com/utgwkk Vertliba V.V. https://github.com/vertliba Vince West https://github.com/dvincentwest ZEDGR https://github.com/ZEDGR ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1709131730.0 pyperclip-1.11.0/LICENSE.txt0000644000076500000240000000271714567643722013772 0ustar00alstaffCopyright (c) 2014, Al Sweigart All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the {organization} nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1758897619.009825 pyperclip-1.11.0/PKG-INFO0000644000076500000240000000461515065522723013232 0ustar00alstaffMetadata-Version: 2.4 Name: pyperclip Version: 1.11.0 Summary: A cross-platform clipboard module for Python. (Only handles plain text for now.) Author-email: Al Sweigart License: BSD Project-URL: Homepage, https://github.com/asweigart/pyperclip Keywords: clipboard,copy,paste,clip,xsel,xclip Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Win32 (MS Windows) Classifier: Environment :: X11 Applications Classifier: Environment :: MacOS X Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 Description-Content-Type: text/markdown License-File: LICENSE.txt License-File: AUTHORS.txt Dynamic: license-file Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with Python 2 and 3. Install on Windows: `pip install pyperclip` Install on Linux/macOS: `pip3 install pyperclip` Al Sweigart al@inventwithpython.com BSD License Example Usage ============= >>> import pyperclip >>> pyperclip.copy('The text to be copied to the clipboard.') >>> pyperclip.paste() 'The text to be copied to the clipboard.' Currently only handles plaintext. On Windows, no additional modules are needed. On Mac, this module makes use of the pbcopy and pbpaste commands, which should come with the os. On Linux, this module makes use of the xclip or xsel commands, which should come with the os. Otherwise run "sudo apt-get install xclip" or "sudo apt-get install xsel" (Note: xsel does not always seem to work.) Otherwise on Linux, you will need the qtpy or PyQT5 modules installed. Support ------- If you find this project helpful and would like to support its development, [consider donating to its creator on Patreon](https://www.patreon.com/AlSweigart). ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1758155924.0 pyperclip-1.11.0/README.md0000644000076500000240000000210515062652224013401 0ustar00alstaffPyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with Python 2 and 3. Install on Windows: `pip install pyperclip` Install on Linux/macOS: `pip3 install pyperclip` Al Sweigart al@inventwithpython.com BSD License Example Usage ============= >>> import pyperclip >>> pyperclip.copy('The text to be copied to the clipboard.') >>> pyperclip.paste() 'The text to be copied to the clipboard.' Currently only handles plaintext. On Windows, no additional modules are needed. On Mac, this module makes use of the pbcopy and pbpaste commands, which should come with the os. On Linux, this module makes use of the xclip or xsel commands, which should come with the os. Otherwise run "sudo apt-get install xclip" or "sudo apt-get install xsel" (Note: xsel does not always seem to work.) Otherwise on Linux, you will need the qtpy or PyQT5 modules installed. Support ------- If you find this project helpful and would like to support its development, [consider donating to its creator on Patreon](https://www.patreon.com/AlSweigart). ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1758897577.0 pyperclip-1.11.0/pyproject.toml0000644000076500000240000000302115065522651015037 0ustar00alstaff[build-system] requires = ["setuptools>=61"] build-backend = "setuptools.build_meta" [project] name = "pyperclip" dynamic = ["version"] description = "A cross-platform clipboard module for Python. (Only handles plain text for now.)" readme = "README.md" authors = [ { name = "Al Sweigart", email = "al@inventwithpython.com" } ] license = { text = "BSD" } keywords = ["clipboard", "copy", "paste", "clip", "xsel", "xclip"] classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Win32 (MS Windows)", "Environment :: X11 Applications", "Environment :: MacOS X", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", ] [project.urls] Homepage = "https://github.com/asweigart/pyperclip" [tool.setuptools] package-dir = {"" = "src"} [tool.setuptools.packages.find] where = ["src"] [tool.setuptools.dynamic] version = { attr = "pyperclip.__version__" } [tool.pytest.ini_options] testpaths = ["tests"] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1758897619.0100434 pyperclip-1.11.0/setup.cfg0000644000076500000240000000004615065522723013750 0ustar00alstaff[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1758897619.007938 pyperclip-1.11.0/src/0000755000076500000240000000000015065522723012716 5ustar00alstaff././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1758897619.0086536 pyperclip-1.11.0/src/pyperclip/0000755000076500000240000000000015065522723014725 5ustar00alstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1758897606.0 pyperclip-1.11.0/src/pyperclip/__init__.py0000644000076500000240000005545715065522706017057 0ustar00alstaff""" Pyperclip A cross-platform clipboard module for Python, with copy & paste functions for plain text. By Al Sweigart al@inventwithpython.com BSD License Usage: import pyperclip pyperclip.copy('The text to be copied to the clipboard.') spam = pyperclip.paste() if not pyperclip.is_available(): print("Copy functionality unavailable!") On Windows, no additional modules are needed. On Mac, the pyobjc module is used, falling back to the pbcopy and pbpaste cli commands. (These commands should come with OS X.). On Linux, install xclip, xsel, or wl-clipboard (for "wayland" sessions) via package manager. For example, in Debian: sudo apt-get install xclip sudo apt-get install xsel sudo apt-get install wl-clipboard Otherwise on Linux, you will need the qtpy or PyQt5 modules installed. This module does not work with PyGObject yet. Cygwin is currently not supported. Security Note: This module runs programs with these names: - which - pbcopy - pbpaste - xclip - xsel - wl-copy/wl-paste - klipper - qdbus A malicious user could rename or add programs with these names, tricking Pyperclip into running them with whatever permissions the Python process has. """ __version__ = '1.11.0' import base64 import contextlib import ctypes import os import platform import subprocess import sys import time import warnings from ctypes import c_size_t, sizeof, c_wchar_p, get_errno, c_wchar from typing import Union, Optional _IS_RUNNING_PYTHON_2 = sys.version_info[0] == 2 # type: bool # For paste(): Python 3 uses str, Python 2 uses unicode. if _IS_RUNNING_PYTHON_2: # mypy complains about `unicode` for Python 2, so we ignore the type error: _PYTHON_STR_TYPE = unicode # type: ignore else: _PYTHON_STR_TYPE = str ENCODING = 'utf-8' # type: str try: # Use shutil.which() for Python 3+ from shutil import which def _py3_executable_exists(name): # type: (str) -> bool return bool(which(name)) _executable_exists = _py3_executable_exists except ImportError: # Use the "which" unix command for Python 2.7 and prior. def _py2_executable_exists(name): # type: (str) -> bool return subprocess.call(['which', name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0 _executable_exists = _py2_executable_exists # Exceptions class PyperclipException(RuntimeError): pass class PyperclipWindowsException(PyperclipException): def __init__(self, message): message += " (%s)" % ctypes.WinError() super(PyperclipWindowsException, self).__init__(message) class PyperclipTimeoutException(PyperclipException): pass def init_osx_pbcopy_clipboard(): def copy_osx_pbcopy(text): text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. p = subprocess.Popen(['pbcopy', 'w'], stdin=subprocess.PIPE, close_fds=True) p.communicate(input=text.encode(ENCODING)) def paste_osx_pbcopy(): p = subprocess.Popen(['pbpaste', 'r'], stdout=subprocess.PIPE, close_fds=True) stdout, stderr = p.communicate() return stdout.decode(ENCODING) return copy_osx_pbcopy, paste_osx_pbcopy def init_osx_pyobjc_clipboard(): def copy_osx_pyobjc(text): '''Copy string argument to clipboard''' text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. newStr = Foundation.NSString.stringWithString_(text).nsstring() newData = newStr.dataUsingEncoding_(Foundation.NSUTF8StringEncoding) board = AppKit.NSPasteboard.generalPasteboard() board.declareTypes_owner_([AppKit.NSStringPboardType], None) board.setData_forType_(newData, AppKit.NSStringPboardType) def paste_osx_pyobjc(): "Returns contents of clipboard" board = AppKit.NSPasteboard.generalPasteboard() content = board.stringForType_(AppKit.NSStringPboardType) return content return copy_osx_pyobjc, paste_osx_pyobjc def init_qt_clipboard(): global QApplication # $DISPLAY should exist # Try to import from qtpy, but if that fails try PyQt5 try: from qtpy.QtWidgets import QApplication except: from PyQt5.QtWidgets import QApplication app = QApplication.instance() if app is None: app = QApplication([]) def copy_qt(text): text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. cb = app.clipboard() cb.setText(text) def paste_qt(): cb = app.clipboard() return _PYTHON_STR_TYPE(cb.text()) return copy_qt, paste_qt def init_xclip_clipboard(): DEFAULT_SELECTION='c' PRIMARY_SELECTION='p' def copy_xclip(text, primary=False): text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. selection=DEFAULT_SELECTION if primary: selection=PRIMARY_SELECTION p = subprocess.Popen(['xclip', '-selection', selection], stdin=subprocess.PIPE, close_fds=True) p.communicate(input=text.encode(ENCODING)) def paste_xclip(primary=False): selection=DEFAULT_SELECTION if primary: selection=PRIMARY_SELECTION p = subprocess.Popen(['xclip', '-selection', selection, '-o'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) stdout, stderr = p.communicate() # Intentionally ignore extraneous output on stderr when clipboard is empty return stdout.decode(ENCODING) return copy_xclip, paste_xclip def init_xsel_clipboard(): DEFAULT_SELECTION='-b' PRIMARY_SELECTION='-p' def copy_xsel(text, primary=False): text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. selection_flag = DEFAULT_SELECTION if primary: selection_flag = PRIMARY_SELECTION p = subprocess.Popen(['xsel', selection_flag, '-i'], stdin=subprocess.PIPE, close_fds=True) p.communicate(input=text.encode(ENCODING)) def paste_xsel(primary=False): selection_flag = DEFAULT_SELECTION if primary: selection_flag = PRIMARY_SELECTION p = subprocess.Popen(['xsel', selection_flag, '-o'], stdout=subprocess.PIPE, close_fds=True) stdout, stderr = p.communicate() return stdout.decode(ENCODING) return copy_xsel, paste_xsel def init_wl_clipboard(): PRIMARY_SELECTION = "-p" def copy_wl(text, primary=False): text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. args = ["wl-copy"] if primary: args.append(PRIMARY_SELECTION) if not text: args.append('--clear') subprocess.check_call(args, close_fds=True) else: pass p = subprocess.Popen(args, stdin=subprocess.PIPE, close_fds=True) p.communicate(input=text.encode(ENCODING)) def paste_wl(primary=False): args = ["wl-paste", "-n", "-t", "text"] if primary: args.append(PRIMARY_SELECTION) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) stdout, _stderr = p.communicate() return stdout.decode(ENCODING) return copy_wl, paste_wl def init_klipper_clipboard(): def copy_klipper(text): text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. p = subprocess.Popen( ['qdbus', 'org.kde.klipper', '/klipper', 'setClipboardContents', text.encode(ENCODING)], stdin=subprocess.PIPE, close_fds=True) p.communicate(input=None) def paste_klipper(): p = subprocess.Popen( ['qdbus', 'org.kde.klipper', '/klipper', 'getClipboardContents'], stdout=subprocess.PIPE, close_fds=True) stdout, stderr = p.communicate() # Workaround for https://bugs.kde.org/show_bug.cgi?id=342874 # TODO: https://github.com/asweigart/pyperclip/issues/43 clipboardContents = stdout.decode(ENCODING) # even if blank, Klipper will append a newline at the end assert len(clipboardContents) > 0 # make sure that newline is there assert clipboardContents.endswith('\n') if clipboardContents.endswith('\n'): clipboardContents = clipboardContents[:-1] return clipboardContents return copy_klipper, paste_klipper def init_dev_clipboard_clipboard(): def copy_dev_clipboard(text): text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. if text == '': warnings.warn('Pyperclip cannot copy a blank string to the clipboard on Cygwin. This is effectively a no-op.') if '\r' in text: warnings.warn('Pyperclip cannot handle \\r characters on Cygwin.') fo = open('/dev/clipboard', 'wt') fo.write(text) fo.close() def paste_dev_clipboard(): fo = open('/dev/clipboard', 'rt') content = fo.read() fo.close() return content return copy_dev_clipboard, paste_dev_clipboard def init_no_clipboard(): class ClipboardUnavailable(object): def __call__(self, *args, **kwargs): additionalInfo = '' if sys.platform == 'linux': additionalInfo = '\nOn Linux, you can run `sudo apt-get install xclip`, `sudo apt-get install xselect` (on X11) or `sudo apt-get install wl-clipboard` (on Wayland) to install a copy/paste mechanism.' raise PyperclipException('Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error' + additionalInfo) if _IS_RUNNING_PYTHON_2: def __nonzero__(self): return False else: def __bool__(self): return False return ClipboardUnavailable(), ClipboardUnavailable() # Windows-related clipboard functions: class CheckedCall(object): def __init__(self, f): super(CheckedCall, self).__setattr__("f", f) def __call__(self, *args): ret = self.f(*args) if not ret and get_errno(): raise PyperclipWindowsException("Error calling " + self.f.__name__) return ret def __setattr__(self, key, value): setattr(self.f, key, value) def init_windows_clipboard(): global HGLOBAL, LPVOID, DWORD, LPCSTR, INT, HWND, HINSTANCE, HMENU, BOOL, UINT, HANDLE from ctypes.wintypes import (HGLOBAL, LPVOID, DWORD, LPCSTR, INT, HWND, HINSTANCE, HMENU, BOOL, UINT, HANDLE) windll = ctypes.windll msvcrt = ctypes.CDLL('msvcrt') safeCreateWindowExA = CheckedCall(windll.user32.CreateWindowExA) safeCreateWindowExA.argtypes = [DWORD, LPCSTR, LPCSTR, DWORD, INT, INT, INT, INT, HWND, HMENU, HINSTANCE, LPVOID] safeCreateWindowExA.restype = HWND safeDestroyWindow = CheckedCall(windll.user32.DestroyWindow) safeDestroyWindow.argtypes = [HWND] safeDestroyWindow.restype = BOOL OpenClipboard = windll.user32.OpenClipboard OpenClipboard.argtypes = [HWND] OpenClipboard.restype = BOOL safeCloseClipboard = CheckedCall(windll.user32.CloseClipboard) safeCloseClipboard.argtypes = [] safeCloseClipboard.restype = BOOL safeEmptyClipboard = CheckedCall(windll.user32.EmptyClipboard) safeEmptyClipboard.argtypes = [] safeEmptyClipboard.restype = BOOL safeGetClipboardData = CheckedCall(windll.user32.GetClipboardData) safeGetClipboardData.argtypes = [UINT] safeGetClipboardData.restype = HANDLE safeSetClipboardData = CheckedCall(windll.user32.SetClipboardData) safeSetClipboardData.argtypes = [UINT, HANDLE] safeSetClipboardData.restype = HANDLE safeGlobalAlloc = CheckedCall(windll.kernel32.GlobalAlloc) safeGlobalAlloc.argtypes = [UINT, c_size_t] safeGlobalAlloc.restype = HGLOBAL safeGlobalLock = CheckedCall(windll.kernel32.GlobalLock) safeGlobalLock.argtypes = [HGLOBAL] safeGlobalLock.restype = LPVOID safeGlobalUnlock = CheckedCall(windll.kernel32.GlobalUnlock) safeGlobalUnlock.argtypes = [HGLOBAL] safeGlobalUnlock.restype = BOOL wcslen = CheckedCall(msvcrt.wcslen) wcslen.argtypes = [c_wchar_p] wcslen.restype = UINT GMEM_MOVEABLE = 0x0002 CF_UNICODETEXT = 13 @contextlib.contextmanager def window(): """ Context that provides a valid Windows hwnd. """ # we really just need the hwnd, so setting "STATIC" # as predefined lpClass is just fine. hwnd = safeCreateWindowExA(0, b"STATIC", None, 0, 0, 0, 0, 0, None, None, None, None) try: yield hwnd finally: safeDestroyWindow(hwnd) @contextlib.contextmanager def clipboard(hwnd): """ Context manager that opens the clipboard and prevents other applications from modifying the clipboard content. """ # We may not get the clipboard handle immediately because # some other application is accessing it (?) # We try for at least 500ms to get the clipboard. t = time.time() + 0.5 success = False while time.time() < t: success = OpenClipboard(hwnd) if success: break time.sleep(0.01) if not success: raise PyperclipWindowsException("Error calling OpenClipboard") try: yield finally: safeCloseClipboard() def copy_windows(text): # This function is heavily based on # http://msdn.com/ms649016#_win32_Copying_Information_to_the_Clipboard text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. with window() as hwnd: # http://msdn.com/ms649048 # If an application calls OpenClipboard with hwnd set to NULL, # EmptyClipboard sets the clipboard owner to NULL; # this causes SetClipboardData to fail. # => We need a valid hwnd to copy something. with clipboard(hwnd): safeEmptyClipboard() if text: # http://msdn.com/ms649051 # If the hMem parameter identifies a memory object, # the object must have been allocated using the # function with the GMEM_MOVEABLE flag. count = wcslen(text) + 1 handle = safeGlobalAlloc(GMEM_MOVEABLE, count * sizeof(c_wchar)) locked_handle = safeGlobalLock(handle) ctypes.memmove(c_wchar_p(locked_handle), c_wchar_p(text), count * sizeof(c_wchar)) safeGlobalUnlock(handle) safeSetClipboardData(CF_UNICODETEXT, handle) def paste_windows(): with clipboard(None): handle = safeGetClipboardData(CF_UNICODETEXT) if not handle: # GetClipboardData may return NULL with errno == NO_ERROR # if the clipboard is empty. # (Also, it may return a handle to an empty buffer, # but technically that's not empty) return "" locked_handle = safeGlobalLock(handle) return_value = c_wchar_p(locked_handle).value safeGlobalUnlock(handle) return return_value return copy_windows, paste_windows def init_wsl_clipboard(): def copy_wsl(text): text = _PYTHON_STR_TYPE(text) # Converts non-str values to str. p = subprocess.Popen(['clip.exe'], stdin=subprocess.PIPE, close_fds=True) p.communicate(input=text.encode('utf-16le')) def paste_wsl(): ps_script = '[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes((Get-Clipboard -Raw)))' # '-noprofile' speeds up load time p = subprocess.Popen(['powershell.exe', '-noprofile', '-command', ps_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) stdout, stderr = p.communicate() if stderr: raise Exception(f"Error pasting from clipboard: {stderr}") try: base64_encoded = stdout.decode('utf-8').strip() decoded_bytes = base64.b64decode(base64_encoded) return decoded_bytes.decode('utf-8') except Exception as e: raise RuntimeError(f"Decoding error: {e}") return copy_wsl, paste_wsl # Automatic detection of clipboard mechanisms and importing is done in determine_clipboard(): def determine_clipboard(): ''' Determine the OS/platform and set the copy() and paste() functions accordingly. ''' global Foundation, AppKit, qtpy, PyQt5 # Setup for the CYGWIN platform: if 'cygwin' in platform.system().lower(): # Cygwin has a variety of values returned by platform.system(), such as 'CYGWIN_NT-6.1' # FIXME: pyperclip currently does not support Cygwin, # see https://github.com/asweigart/pyperclip/issues/55 if os.path.exists('/dev/clipboard'): warnings.warn('Pyperclip\'s support for Cygwin is not perfect, see https://github.com/asweigart/pyperclip/issues/55') return init_dev_clipboard_clipboard() # Setup for the WINDOWS platform: elif os.name == 'nt' or platform.system() == 'Windows': return init_windows_clipboard() if platform.system() == 'Linux' and os.path.isfile('/proc/version'): with open('/proc/version', 'r') as f: if "microsoft" in f.read().lower(): return init_wsl_clipboard() # Setup for the MAC OS X platform: if os.name == 'mac' or platform.system() == 'Darwin': try: import Foundation # check if pyobjc is installed import AppKit except ImportError: return init_osx_pbcopy_clipboard() else: return init_osx_pyobjc_clipboard() # Setup for the LINUX platform: if os.getenv("WAYLAND_DISPLAY") and _executable_exists("wl-copy") and _executable_exists("wl-paste"): return init_wl_clipboard() # `import PyQt4` sys.exit()s if DISPLAY is not in the environment. # Thus, we need to detect the presence of $DISPLAY manually # and not load PyQt4 if it is absent. elif os.getenv("DISPLAY"): if _executable_exists("xclip"): # Note: 2024/06/18 Google Trends shows xclip as more popular than xsel. return init_xclip_clipboard() if _executable_exists("xsel"): return init_xsel_clipboard() if _executable_exists("klipper") and _executable_exists("qdbus"): return init_klipper_clipboard() try: # qtpy is a small abstraction layer that lets you write # applications using a single api call to either PyQt or PySide. # https://pypi.python.org/pypi/QtPy import qtpy # check if qtpy is installed return init_qt_clipboard() except ImportError: pass # If qtpy isn't installed, fall back on importing PyQt5 try: import PyQt5 # check if PyQt5 is installed return init_qt_clipboard() except ImportError: pass return init_no_clipboard() def set_clipboard(clipboard): ''' Explicitly sets the clipboard mechanism. The "clipboard mechanism" is how the copy() and paste() functions interact with the operating system to implement the copy/paste feature. The clipboard parameter must be one of: - pbcopy - pbobjc (default on Mac OS X) - qt - xclip - xsel - klipper - windows (default on Windows) - no (this is what is set when no clipboard mechanism can be found) ''' global copy, paste clipboard_types = { "pbcopy": init_osx_pbcopy_clipboard, "pyobjc": init_osx_pyobjc_clipboard, "qt": init_qt_clipboard, # TODO - split this into 'qtpy' and 'pyqt5' "xclip": init_xclip_clipboard, "xsel": init_xsel_clipboard, "wl-clipboard": init_wl_clipboard, "klipper": init_klipper_clipboard, "windows": init_windows_clipboard, "no": init_no_clipboard, } if clipboard not in clipboard_types: raise ValueError('Argument must be one of %s' % (', '.join([repr(_) for _ in clipboard_types.keys()]))) # Sets pyperclip's copy() and paste() functions: copy, paste = clipboard_types[clipboard]() def lazy_load_stub_copy(text): ''' A stub function for copy(), which will load the real copy() function when called so that the real copy() function is used for later calls. This allows users to import pyperclip without having determine_clipboard() automatically run, which will automatically select a clipboard mechanism. This could be a problem if it selects, say, the memory-heavy PyQt5 module but the user was just going to immediately call set_clipboard() to use a different clipboard mechanism. The lazy loading this stub function implements gives the user a chance to call set_clipboard() to pick another clipboard mechanism. Or, if the user simply calls copy() or paste() without calling set_clipboard() first, will fall back on whatever clipboard mechanism that determine_clipboard() automatically chooses. ''' global copy, paste copy, paste = determine_clipboard() return copy(text) def lazy_load_stub_paste(): ''' A stub function for paste(), which will load the real paste() function when called so that the real paste() function is used for later calls. This allows users to import pyperclip without having determine_clipboard() automatically run, which will automatically select a clipboard mechanism. This could be a problem if it selects, say, the memory-heavy PyQt5 module but the user was just going to immediately call set_clipboard() to use a different clipboard mechanism. The lazy loading this stub function implements gives the user a chance to call set_clipboard() to pick another clipboard mechanism. Or, if the user simply calls copy() or paste() without calling set_clipboard() first, will fall back on whatever clipboard mechanism that determine_clipboard() automatically chooses. ''' global copy, paste copy, paste = determine_clipboard() return paste() def is_available(): return copy != lazy_load_stub_copy and paste != lazy_load_stub_paste # Initially, copy() and paste() are set to lazy loading wrappers which will # set `copy` and `paste` to real functions the first time they're used, unless # set_clipboard() or determine_clipboard() is called first. copy, paste = lazy_load_stub_copy, lazy_load_stub_paste __all__ = ['copy', 'paste', 'set_clipboard', 'determine_clipboard'] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1709131730.0 pyperclip-1.11.0/src/pyperclip/__main__.py0000644000076500000240000000135414567643722017033 0ustar00alstaffimport pyperclip import sys if len(sys.argv) > 1 and sys.argv[1] in ('-c', '--copy'): if len(sys.argv) > 2: pyperclip.copy(sys.argv[2]) else: pyperclip.copy(sys.stdin.read()) elif len(sys.argv) > 1 and sys.argv[1] in ('-p', '--paste'): sys.stdout.write(pyperclip.paste()) else: print('Usage: python -m pyperclip [-c | --copy] [text_to_copy] | [-p | --paste]') print() print('If a text_to_copy argument is provided, it is copied to the') print('clipboard. Otherwise, the stdin stream is copied to the') print('clipboard. (If reading this in from the keyboard, press') print('CTRL-Z on Windows or CTRL-D on Linux/macOS to stop.') print('When pasting, the clipboard will be written to stdout.')././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1758897619.0096655 pyperclip-1.11.0/src/pyperclip.egg-info/0000755000076500000240000000000015065522723016417 5ustar00alstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1758897619.0 pyperclip-1.11.0/src/pyperclip.egg-info/PKG-INFO0000644000076500000240000000461515065522723017522 0ustar00alstaffMetadata-Version: 2.4 Name: pyperclip Version: 1.11.0 Summary: A cross-platform clipboard module for Python. (Only handles plain text for now.) Author-email: Al Sweigart License: BSD Project-URL: Homepage, https://github.com/asweigart/pyperclip Keywords: clipboard,copy,paste,clip,xsel,xclip Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Win32 (MS Windows) Classifier: Environment :: X11 Applications Classifier: Environment :: MacOS X Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 Description-Content-Type: text/markdown License-File: LICENSE.txt License-File: AUTHORS.txt Dynamic: license-file Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with Python 2 and 3. Install on Windows: `pip install pyperclip` Install on Linux/macOS: `pip3 install pyperclip` Al Sweigart al@inventwithpython.com BSD License Example Usage ============= >>> import pyperclip >>> pyperclip.copy('The text to be copied to the clipboard.') >>> pyperclip.paste() 'The text to be copied to the clipboard.' Currently only handles plaintext. On Windows, no additional modules are needed. On Mac, this module makes use of the pbcopy and pbpaste commands, which should come with the os. On Linux, this module makes use of the xclip or xsel commands, which should come with the os. Otherwise run "sudo apt-get install xclip" or "sudo apt-get install xsel" (Note: xsel does not always seem to work.) Otherwise on Linux, you will need the qtpy or PyQT5 modules installed. Support ------- If you find this project helpful and would like to support its development, [consider donating to its creator on Patreon](https://www.patreon.com/AlSweigart). ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1758897619.0 pyperclip-1.11.0/src/pyperclip.egg-info/SOURCES.txt0000644000076500000240000000042015065522723020277 0ustar00alstaffAUTHORS.txt LICENSE.txt README.md pyproject.toml src/pyperclip/__init__.py src/pyperclip/__main__.py src/pyperclip.egg-info/PKG-INFO src/pyperclip.egg-info/SOURCES.txt src/pyperclip.egg-info/dependency_links.txt src/pyperclip.egg-info/top_level.txt tests/test_pyperclip.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1758897619.0 pyperclip-1.11.0/src/pyperclip.egg-info/dependency_links.txt0000644000076500000240000000000115065522723022465 0ustar00alstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1758897619.0 pyperclip-1.11.0/src/pyperclip.egg-info/top_level.txt0000644000076500000240000000001215065522723021142 0ustar00alstaffpyperclip ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1758897619.009353 pyperclip-1.11.0/tests/0000755000076500000240000000000015065522723013271 5ustar00alstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1758155924.0 pyperclip-1.11.0/tests/test_pyperclip.py0000644000076500000240000001156715062652224016720 0ustar00alstaff# coding: utf-8 import string import unittest import random import os import platform #import sys #sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) from pyperclip import _executable_exists, HAS_DISPLAY from pyperclip import (init_osx_pbcopy_clipboard, init_osx_pyobjc_clipboard, init_dev_clipboard_clipboard, init_qt_clipboard, init_xclip_clipboard, init_xsel_clipboard, init_wl_clipboard, init_klipper_clipboard, init_no_clipboard) from pyperclip import init_windows_clipboard from pyperclip import init_wsl_clipboard from pyperclip import PyperclipException random.seed(42) # Make the "random" tests reproducible. class _TestClipboard(unittest.TestCase): clipboard = None supports_unicode = True @property def copy(self): return self.clipboard[0] @property def paste(self): return self.clipboard[1] def setUp(self): if not self.clipboard: self.skipTest("Clipboard not supported.") def test_copy_simple(self): self.copy("pyper\r\nclip") def test_copy_paste_simple(self): msg = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(1000)) self.copy(msg) self.assertEqual(self.paste(), msg) def test_copy_paste_whitespace(self): msg = ''.join(random.choice(string.whitespace) for _ in range(1000)) self.copy(msg) self.assertEqual(self.paste(), msg) def test_copy_blank(self): self.copy('TEST') self.copy('') self.assertEqual(self.paste(), '') def test_copy_unicode(self): if not self.supports_unicode: raise unittest.SkipTest() self.copy(u"ಠ_ಠ") def test_copy_unicode_emoji(self): if not self.supports_unicode: raise unittest.SkipTest() self.copy(u"🙆") def test_copy_paste_unicode(self): if not self.supports_unicode: raise unittest.SkipTest() msg = u"ಠ_ಠ" self.copy(msg) self.assertEqual(self.paste(), msg) def test_copy_paste_unicode_emoji(self): if not self.supports_unicode: raise unittest.SkipTest() msg = u"🙆" self.copy(msg) self.assertEqual(self.paste(), msg) def test_non_str(self): # Test copying an int. self.copy(42) self.assertEqual(self.paste(), '42') self.copy(-1) self.assertEqual(self.paste(), '-1') # Test copying a float. self.copy(3.141592) self.assertEqual(self.paste(), '3.141592') # Test copying bools. self.copy(True) self.assertEqual(self.paste(), 'True') self.copy(False) self.assertEqual(self.paste(), 'False') # All other non-str values raise an exception. with self.assertRaises(PyperclipException): self.copy(None) with self.assertRaises(PyperclipException): self.copy([2, 4, 6, 8]) class TestCygwin(_TestClipboard): if 'cygwin' in platform.system().lower(): clipboard = init_dev_clipboard_clipboard() class TestWindows(_TestClipboard): if os.name == 'nt' or platform.system() == 'Windows': clipboard = init_windows_clipboard() class TestWSL(_TestClipboard): if platform.system() == 'Linux': with open('/proc/version', 'r') as f: if "Microsoft" in f.read(): clipboard = init_wsl_clipboard() class TestOSX(_TestClipboard): if os.name == 'mac' or platform.system() == 'Darwin': try: import Foundation # check if pyobjc is installed import AppKit except ImportError: clipboard = init_osx_pbcopy_clipboard() # TODO else: clipboard = init_osx_pyobjc_clipboard() class TestQt(_TestClipboard): if HAS_DISPLAY: try: import PyQt5.QtWidgets except ImportError: pass else: clipboard = init_qt_clipboard() class TestXClip(_TestClipboard): if _executable_exists("xclip"): clipboard = init_xclip_clipboard() class TestXSel(_TestClipboard): if _executable_exists("xsel"): clipboard = init_xsel_clipboard() class TestWlClipboard(_TestClipboard): if _executable_exists("wl-copy"): clipboard = init_wl_clipboard() class TestKlipper(_TestClipboard): if _executable_exists("klipper") and _executable_exists("qdbus"): clipboard = init_klipper_clipboard() class TestNoClipboard(unittest.TestCase): copy, paste = init_no_clipboard() def test_copy(self): with self.assertRaises(RuntimeError): self.copy("foo") def test_paste(self): with self.assertRaises(RuntimeError): self.paste() if __name__ == '__main__': unittest.main()