### Install pyclip Source: https://pyclip.readthedocs.io/en/latest/index.html Use pip to install the pyclip library. Requires Python 3.7 or later. ```bash pip install pyclip ``` -------------------------------- ### Initialize Windows Clipboard Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/win_clip.html Raises ClipboardSetupException if pywin32 is not installed. This is required for Windows clipboard operations. ```python if _win32clipboard is None or _win32con is None: raise ClipboardSetupException("pywin32 must be installed to use this library on Windows platform.") self._clipboard = _Win32Clipboard() ``` -------------------------------- ### Initialize XclipClipboard Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/xclip_clip.html Initializes the XclipClipboard class. It checks for the presence of the 'xclip' executable and raises a ClipboardSetupException if it's not found, indicating that xclip must be installed. ```python class XclipClipboard(ClipboardBase): def __init__(self): self.xclip = shutil.which('xclip') if not self.xclip: raise ClipboardSetupException( "xclip must be installed. " "Please install xclip using your system package manager" ) ``` -------------------------------- ### Clipboard Initialization and Exception Handling Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/__init__.html Handles the detection of the default clipboard and catches potential setup exceptions. If an exception occurs, the default clipboard is set to None and the exception traceback is stored. ```python import sys from .util import detect_clipboard from .base import ClipboardSetupException from functools import wraps try: DEFAULT_CLIPBOARD = detect_clipboard() except ClipboardSetupException as e: DEFAULT_CLIPBOARD = None _CLIPBOARD_EXCEPTION_TB = sys.exc_info()[2] ``` -------------------------------- ### Define Clipboard Exceptions Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/base.html Custom exceptions for clipboard operations. `ClipboardException` is the base, and `ClipboardSetupException` indicates issues during setup. ```python # Copyright 2021 Spencer Phillip Young # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` ```python from abc import ABC, abstractmethod from typing import Union [docs]class ClipboardException(Exception): ... [docs]class ClipboardSetupException(ClipboardException): ... ``` -------------------------------- ### PyClip Console Script Source: https://pyclip.readthedocs.io/en/latest/README.html Shows how to use the `pyclip` console script, installed via pip, to copy content from a file to the clipboard. ```bash pyclip copy < my_file.txt ``` -------------------------------- ### PyClip CLI Usage Source: https://pyclip.readthedocs.io/en/latest/README.html Examples of using the pyclip command-line interface to paste clipboard contents to stdout or copy content from stdin to the clipboard. ```bash # paste clipboard contents to stdout python -m pyclip paste # load contents to the clipboard from stdin python -m pyclip copy < myfile.text # same as above, but pipe from another command some-program | python -m pyclip copy ``` -------------------------------- ### Get All Clipboard Formats (pyclip) Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/win_clip.html Retrieves all available clipboard formats and their data. Useful for debugging purposes. It handles potential pywintypes errors during data retrieval. ```python def _get_all_formats(self) -> Dict[Tuple[int, str], Any]: # pragma: no cover """ Unused. Useful for debugging. :return: """ import pywintypes d = {} formats = self._clipboard._enumerate_clipboard_formats() with self._clipboard as clip: for fmt in formats: name = self._clipboard._get_format_name(fmt) try: d[(fmt, name)] = clip.GetClipboardData(fmt) except pywintypes.error as e: if e.winerror == 0: warnings.warn(f"Could not retrieve clipboard data for format {name} ({fmt}). Skipping.") continue raise return d ``` -------------------------------- ### Initialize pbcopy/pbpaste Backend Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Initializes the _PBCopyPBPasteBackend by checking for the presence of pbcopy and pbpaste executables. Raises ClipboardSetupException if either is not found. ```python self.pbcopy = shutil.which('pbcopy') self.pbpaste = shutil.which('pbpaste') if not self.pbcopy: raise ClipboardSetupException("pbcopy not found. pbcopy must be installed and available on PATH") if not self.pbpaste: raise ClipboardSetupException("pbpaste not found. pbpaste must be installed and available on PATH") ``` -------------------------------- ### Initialize Pasteboard Backend Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Initializes the _PasteboardBackend by importing the pasteboard package and creating a Pasteboard instance. Stores the PDF type for byte handling. ```python import pasteboard self.pb = pasteboard.Pasteboard() self._bytes_type = pasteboard.PDF ``` -------------------------------- ### ClipboardSetupException Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/base.html Exception raised when there is an issue setting up the clipboard. ```APIDOC ## Exception: ClipboardSetupException ### Description Exception raised when an error occurs during the setup or initialization of a clipboard implementation. This typically indicates a problem with the environment or the availability of necessary backend tools. ``` -------------------------------- ### pyclip.__init__.copy Source: https://pyclip.readthedocs.io/en/latest/api/index.html Copies the provided content to the system clipboard. ```APIDOC ## copy ### Description Copies the provided content to the system clipboard. ### Method `copy(*args, **kwargs)` ### Parameters This function accepts arbitrary positional and keyword arguments, but they are not used in the core functionality. ``` -------------------------------- ### pyclip.__init__.paste Source: https://pyclip.readthedocs.io/en/latest/api/index.html Retrieves content from the system clipboard. ```APIDOC ## paste ### Description Retrieves content from the system clipboard. ### Method `paste(*args, **kwargs)` ### Parameters This function accepts arbitrary positional and keyword arguments, but they are not used in the core functionality. ``` -------------------------------- ### copy Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/__init__.html Copies the provided arguments to the system clipboard. Raises ClipboardSetupException if the clipboard could not be initialized. ```APIDOC ## copy ### Description Copies the provided arguments to the system clipboard. ### Method `copy(*args, **kwargs)` ### Parameters Accepts arbitrary positional and keyword arguments to be passed to the underlying clipboard's copy method. ### Request Example ```python import pyclip pyclip.copy('Hello, world!') ``` ### Response #### Success Response Returns the result of the underlying clipboard's copy method. #### Response Example ```python # Example return value depends on the underlying clipboard implementation. # Often, this might be None or a boolean indicating success. None ``` ### Error Handling Raises `ClipboardSetupException` if the clipboard could not be initialized during setup. ``` -------------------------------- ### Initialize MacOSClip with Backend Selection Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Initializes the MacOSClip class, attempting to use the pasteboard library. If pasteboard is not available, it falls back to the _PBCopyPBPasteBackend. ```python class MacOSClip(ClipboardBase): """ Provides Clipboard functionality for MacOS. Defers to one of two backends: :py:class:`_PasteboardBackend` (the default) or :py:class:`_PBCopyPBPasteBackend`. """ def __init__(self, _backend=None): if _backend: self.backend = _backend else: try: import pasteboard self.backend = _PasteboardBackend() except ImportError: self.backend = _PBCopyPBPasteBackend() ``` -------------------------------- ### PyClip Entrypoint Source: https://pyclip.readthedocs.io/en/latest/api/index.html This script serves as the main entrypoint for calling PyClip from the command line using `python -m pyclip`. It delegates execution to `pyclip.cli.main`. ```python import pyclip.cli if __name__ == "__main__": pyclip.cli.main() ``` -------------------------------- ### Copy to Clipboard Function Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/__init__.html Copies data to the system clipboard. Raises a ClipboardSetupException if the clipboard could not be initialized. ```python @wrapif def copy(*args, **kwargs): if DEFAULT_CLIPBOARD is None: raise ClipboardSetupException("Could not setup clipboard").with_traceback(_CLIPBOARD_EXCEPTION_TB) return DEFAULT_CLIPBOARD.copy(*args, **kwargs) ``` -------------------------------- ### pyclip.__init__.clear Source: https://pyclip.readthedocs.io/en/latest/api/index.html Clears the system clipboard content. ```APIDOC ## clear ### Description Clears the system clipboard content. ### Method `clear(*args, **kwargs)` ### Parameters This function accepts arbitrary positional and keyword arguments, but they are not used in the core functionality. ``` -------------------------------- ### pyclip.__init__.wrapif Source: https://pyclip.readthedocs.io/en/latest/api/index.html Wraps a function, potentially applying clipboard operations before or after its execution. ```APIDOC ## wrapif ### Description Wraps a function, potentially applying clipboard operations before or after its execution. ### Method `wrapif(f)` ### Parameters - **f** (function) - The function to be wrapped. ``` -------------------------------- ### paste Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/__init__.html Pastes content from the system clipboard. Raises ClipboardSetupException if the clipboard could not be initialized. ```APIDOC ## paste ### Description Pastes content from the system clipboard. ### Method `paste(*args, **kwargs)` ### Parameters Accepts arbitrary positional and keyword arguments to be passed to the underlying clipboard's paste method. ### Request Example ```python import pyclip content = pyclip.paste() print(content) ``` ### Response #### Success Response (200) Returns the content from the clipboard as a string. #### Response Example ```python 'Pasted content from clipboard' ``` ### Error Handling Raises `ClipboardSetupException` if the clipboard could not be initialized during setup. ``` -------------------------------- ### _PBCopyPBPasteBackend Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Provides clipboard functionality for MacOS using the `pbcopy` and `pbpaste` command-line utilities. It handles copying and pasting text and bytes data. ```APIDOC ## `_PBCopyPBPasteBackend.copy(data: Union[str, bytes], encoding: str = None)` ### Description Copies data into the MacOS clipboard. ### Parameters - **data** (Union[str, bytes]) - The data to be copied to the clipboard. Can be a string or bytes. - **encoding** (str, optional) - Specifies the encoding to use, with the same meaning as in `subprocess.Popen`. Ignored if `data` is bytes. ### Returns None ## `_PBCopyPBPasteBackend.paste(encoding=None, text=None, errors=None)` ### Description Retrieves data from the MacOS clipboard. ### Parameters - **encoding** (str, optional) - Specifies the encoding to use, with the same meaning as in `subprocess.run`. - **text** (bool, optional) - If True, the result type is str. Otherwise, the result type is bytes by default. - **errors** (str, optional) - Specifies how encoding errors are handled, with the same meaning as in `subprocess.run`. ### Returns Union[str, bytes] - The clipboard contents. Returns bytes by default unless `encoding`, `errors`, or `text` are specified, in which case it returns a string. ## `_PBCopyPBPasteBackend.clear()` ### Description Clears the contents of the MacOS clipboard. ### Returns None ``` -------------------------------- ### clear Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/__init__.html Clears the content of the system clipboard. Raises ClipboardSetupException if the clipboard could not be initialized. ```APIDOC ## clear ### Description Clears the content of the system clipboard. ### Method `clear(*args, **kwargs)` ### Parameters Accepts arbitrary positional and keyword arguments to be passed to the underlying clipboard's clear method. ### Request Example ```python import pyclip pyclip.clear() ``` ### Response #### Success Response Returns the result of the underlying clipboard's clear method. #### Response Example ```python # Example return value depends on the underlying clipboard implementation. # Often, this might be None or a boolean indicating success. None ``` ### Error Handling Raises `ClipboardSetupException` if the clipboard could not be initialized during setup. ``` -------------------------------- ### Copy and Paste Text with PyClip Source: https://pyclip.readthedocs.io/en/latest/README.html Demonstrates basic usage of pyclip within a Python script to copy text to the clipboard, paste it back as raw bytes and as text, and then clear the clipboard. ```python import pyclip pyclip.copy("hello clipboard") # copy data to the clipboard cb_data = pyclip.paste() # retrieve clipboard contents print(cb_data) # b'hello clipboard' cb_text = pyclip.paste(text=True) # paste as text print(cb_text) # 'hello clipboard' pyclip.clear() # clears the clipboard contents assert not pyclip.paste() ``` -------------------------------- ### pyclip.cli.main Source: https://pyclip.readthedocs.io/en/latest/api/cli.html The main function for the pyclip command-line interface. This is the primary entry point for users interacting with pyclip via the command line. ```APIDOC ## pyclip.cli.main() ### Description This function serves as the main entry point for the pyclip command-line interface. It handles parsing command-line arguments and executing the appropriate pyclip operations. ### Method `main()` ### Parameters This function does not accept any parameters. ### Usage This function is typically invoked when running the `pyclip` command from the terminal. ``` -------------------------------- ### Paste from Clipboard Function Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/__init__.html Pastes data from the system clipboard. Raises a ClipboardSetupException if the clipboard could not be initialized. ```python @wrapif def paste(*args, **kwargs): if DEFAULT_CLIPBOARD is None: raise ClipboardSetupException("Could not setup clipboard").with_traceback(_CLIPBOARD_EXCEPTION_TB) return DEFAULT_CLIPBOARD.paste(*args, **kwargs) ``` -------------------------------- ### WindowsClipboard.copy Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/win_clip.html Copies data (string or bytes) to the system clipboard. ```APIDOC ## WindowsClipboard.copy ### Description Copies the provided data to the system clipboard. Supports both string and byte data types. ### Method Signature `copy(self, data: Union[str, bytes], encoding=None)` ### Parameters - **data** (Union[str, bytes]) - The data to be copied to the clipboard. Can be a string or bytes. - **encoding** (optional) - The encoding to use if `data` is a string. (Note: This parameter is present in the signature but not explicitly used in the provided source for string handling). ### Request Example ```python from pyclip import WindowsClipboard clipboard = WindowsClipboard() clipboard.copy("Hello, Windows Clipboard!") clipboard.copy(b"\x01\x02\x03") ``` ``` -------------------------------- ### Copy Data using pbcopy Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Copies data (string or bytes) to the clipboard using the pbcopy command. Handles encoding for string data and raises TypeError for unsupported data types. Includes error handling for pbcopy execution. ```python args = [self.pbcopy] if isinstance(data, bytes): if encoding is not None: warnings.warn("encoding specified with a bytes argument. " "Encoding option will be ignored. " "To remove this warning, omit the encoding parameter or specify it as None", stacklevel=2) proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding=encoding) elif isinstance(data, str): proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding=encoding) else: raise TypeError(f"data argument must be of type str or bytes, not {type(data)}") stdout, stderr = proc.communicate(data) if proc.returncode != 0: raise ClipboardException(f"Copy failed. pbcopy returned code: {proc.returncode!r} " f"Stderr: {stderr!r} " f"Stdout: {stdout!r}") return ``` -------------------------------- ### XclipClipboard.copy Source: https://pyclip.readthedocs.io/en/latest/api/xclip_clip.html Copies data to the clipboard. ```APIDOC ## copy(data, encoding=None) ### Description Copies data into the clipboard. ### Parameters #### Path Parameters - **data** (Union[str, bytes]) - Required - the data to be copied to the clipboard. Can be str or bytes. - **encoding** (Optional[str]) - Optional - same meaning as in `subprocess.Popen`. ### Returns None ``` -------------------------------- ### Clear Clipboard Function Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/__init__.html Clears the content of the system clipboard. Raises a ClipboardSetupException if the clipboard could not be initialized. ```python @wrapif def clear(*args, **kwargs): if DEFAULT_CLIPBOARD is None: raise ClipboardSetupException("Could not setup clipboard").with_traceback(_CLIPBOARD_EXCEPTION_TB) return DEFAULT_CLIPBOARD.clear(*args, **kwargs) ``` -------------------------------- ### _PasteboardBackend Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Provides clipboard functionality for MacOS using the `pasteboard` Python package. This backend supports copying string and bytes data. ```APIDOC ## `_PasteboardBackend.copy(data: Union[str, bytes], encoding: str = None)` ### Description Copies data into the MacOS clipboard using the `pasteboard` package. ### Parameters - **data** (Union[str, bytes]) - The data to be copied to the clipboard. Can be a string or bytes. - **encoding** (str, optional) - This parameter is ignored by this backend. ### Returns None ## `_PasteboardBackend.paste(encoding: str = None, text: bool = None, errors: str = None)` ### Description Retrieves contents of the MacOS clipboard using the `pasteboard` package. ### Parameters - **encoding** (str, optional) - Same meaning as in `bytes.encode`. Implies `text=True`. - **text** (bool, optional) - If True, the result will be a string. - **errors** (str, optional) - Same meaning as in `bytes.encode`. Implies `text=True`. ### Returns Union[str, bytes] - The clipboard contents. The return type depends on the parameters provided. ``` -------------------------------- ### Handle HDROP Format Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/win_clip.html Processes HDROP data, expecting a tuple of file paths. Currently supports pasting only a single file. ```python if not isinstance(data, tuple): raise TypeError(f"Unexpected type for HDROP. Data must be tuple, not {type(data)}") if len(data) > 1: raise NotImplementedError("Currently HDROP paste is only supported for single files. It appears multiple files or directories were specified") if len(data) < 1: raise ValueError("Data unexpectedly empty") fname = data[0] if not os.path.isfile(fname): raise ValueError("Can only paste files. Did you copy a directory?") with open(fname, 'rb') as f: return f.read() ``` -------------------------------- ### XclipClipboard.paste Source: https://pyclip.readthedocs.io/en/latest/api/xclip_clip.html Retrieves data from the clipboard. ```APIDOC ## paste(encoding=None, text=None, errors=None) ### Description Retrieves data from the clipboard. ### Parameters #### Path Parameters - **encoding** (Optional[str]) - Optional - same meaning as in `subprocess.run`. - **text** (Optional[bool]) - Optional - same meaning as in `subprocess.run`. - **errors** (Optional[str]) - Optional - same meaning as in `subprocess.run`. ### Returns the clipboard contents. return type is binary by default. If any of `encoding`, `errors`, or `text` are specified, the result type is str ``` -------------------------------- ### WindowsClipboard Class Source: https://pyclip.readthedocs.io/en/latest/api/win_clip.html Represents the clipboard functionality on Windows systems using the pywin32 package. ```APIDOC ## class pyclip.win_clip.WindowsClipboard Provides clipboard functionality for Windows systems. ### Methods #### clear() Clear the clipboard contents. ##### Returns `None` #### copy(data, encoding=None) Copy given string into system clipboard. ##### Parameters - **data** (str) - The string data to copy to the clipboard. - **encoding** (Optional[str]) - The encoding to use for the data. #### paste(encoding=None, text=None, errors=None) Returns clipboard contents. ##### Parameters - **encoding** (Optional[str]) – same meaning as in `bytes.encode`. Implies `text=True` - **text** (Optional[bool]) – if True, bytes object will be returned as str. - **errors** (Optional[str]) – same meaning as in `bytes.encode`. Implies `text=True`. ##### Returns `Union[str, bytes]` - clipboard contents. Return value is bytes by default or str if any of `encoding`, `text`, or `errors` is provided. ``` -------------------------------- ### XclipClipboard.clear Source: https://pyclip.readthedocs.io/en/latest/api/xclip_clip.html Clears the contents of the clipboard. ```APIDOC ## clear() ### Description Clears the clipboard contents. ### Method `clear()` ### Returns None ``` -------------------------------- ### detect_clipboard Source: https://pyclip.readthedocs.io/en/latest/api/util.html Determines the appropriate clipboard implementation to use based on the current operating system platform. ```APIDOC ## detect_clipboard() ### Description Determine what implementation to use based on `sys.platform`. ### Returns - `ClipboardBase` - The detected clipboard implementation class. ``` -------------------------------- ### detect_clipboard Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/util.html Automatically detects and returns an instance of the appropriate clipboard implementation based on the current operating system (sys.platform). It supports macOS, Windows, Linux (Wayland and X11). ```APIDOC ## detect_clipboard() ### Description Determine what clipboard implementation to use based on the operating system. ### Parameters None ### Returns - ClipboardBase: An instance of the detected clipboard implementation. ### Raises - ClipboardSetupException: If no suitable clipboard implementation is found for the current platform. ### Example ```python from pyclip.util import detect_clipboard try: clipboard = detect_clipboard() print(f"Using clipboard: {type(clipboard).__name__}") except Exception as e: print(f"Error detecting clipboard: {e}") ``` ``` -------------------------------- ### Paste Data from Clipboard (Python) Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/xclip_clip.html Retrieves data from the system clipboard using xclip. The return type is binary by default. If encoding, errors, or text parameters are specified, the result is returned as a string. Raises a ClipboardException if xclip returns a non-zero exit code. ```python def paste(self, encoding: str = None, text: bool = None, errors: str = None): """ Retrieve data from the clipboard :param encoding: same meaning as in ``subprocess.run`` :param text: same meaning as in ``subprocess.run`` :param errors: same meaning as in ``subprocess.run`` :return: the clipboard contents. return type is binary by default. If any of ``encoding``, ``errors``, or ``text`` are specified, the result type is str """ args = [self.xclip, '-o', '-selection', 'clipboard'] if encoding or text or errors: completed_proc = subprocess.run( args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=text, encoding=encoding, ) else: completed_proc = subprocess.run( args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if completed_proc.returncode != 0: raise ClipboardException( f"Copy failed. xclip returned code: {completed_proc.returncode!r}" f"Stderr: {completed_proc.stderr!r}" f"Stdout: {completed_proc.stdout!r}" ) return completed_proc.stdout ``` -------------------------------- ### copy() Source: https://pyclip.readthedocs.io/en/latest/genindex.html Copies the provided text content to the clipboard. ```APIDOC ## copy(text: str) ### Description Copies the provided text content to the clipboard. ### Method This is a method available on clipboard objects. ### Endpoint N/A (Python function/method) ### Parameters #### Request Body - **text** (str) - Required - The text content to be copied to the clipboard. ### Request Example ```python import pyclip pyclip.copy('Hello, world!') ``` ### Response None ``` -------------------------------- ### Detect Clipboard Implementation Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/util.html This function determines the correct clipboard implementation based on the operating system. It supports macOS, Windows, Linux (Wayland and X11). Raises an exception if no suitable clipboard is found. ```python # Copyright 2021 Spencer Phillip Young # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os from .base import ClipboardSetupException, ClipboardBase [docs] def detect_clipboard() -> ClipboardBase: """ Determine what implementation to use based on ``sys.platform`` """ if sys.platform == 'darwin': from .macos_clip import MacOSClip return MacOSClip() elif sys.platform == 'win32': from .win_clip import WindowsClipboard return WindowsClipboard() elif sys.platform == 'linux' and os.environ.get("WAYLAND_DISPLAY"): from .wayland_clip import WaylandClipboard return WaylandClipboard() elif sys.platform == 'linux': from .xclip_clip import XclipClipboard return XclipClipboard() else: raise ClipboardSetupException("No suitable clipboard found.") ``` -------------------------------- ### ClipboardBase Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/base.html Abstract base class for Clipboard implementations. Users should not instantiate this class directly but rather use one of its concrete subclasses. ```APIDOC ## Class: ClipboardBase ### Description Abstract base class for Clipboard implementations. This class defines the interface that all concrete clipboard classes must adhere to. ### Methods #### copy(data: Union[str, bytes], encoding: str = None) - **Description**: Copies the provided data to the clipboard. - **Parameters**: - `data` (Union[str, bytes]): The data to be copied. Can be a string or bytes. - `encoding` (str, optional): The encoding to use if `data` is a string. Defaults to None. #### paste(encoding=None, text=None, errors=None) -> Union[str, bytes] - **Description**: Pastes data from the clipboard. - **Parameters**: - `encoding` (str, optional): The encoding to use when decoding the clipboard content if it's bytes. Defaults to None. - `text` (bool, optional): If True, ensures the returned data is a string. If False, ensures the returned data is bytes. If None, the type is determined by the clipboard implementation. Defaults to None. - `errors` (str, optional): Specifies how encoding errors are handled. Defaults to None. - **Returns**: Union[str, bytes] - The data retrieved from the clipboard. #### clear() - **Description**: Clears the content of the clipboard. ``` -------------------------------- ### Copy to Clipboard on MacOS Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Wraps the copy method of the selected backend to perform copy operations on the macOS clipboard. ```python @wraps(_PasteboardBackend.copy) def copy(self, *args, **kwargs): return self.backend.copy(*args, **kwargs) ``` -------------------------------- ### Copy Data to Clipboard (Python) Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/xclip_clip.html Copies data to the system clipboard using xclip. Supports both string and byte data. If a string is provided, it uses text mode for subprocess communication. A warning is issued if an encoding is specified with byte data. ```python def copy(self, data: Union[str, bytes], encoding: str = None) -> None: """ Copy data into the clipboard :param data: the data to be copied to the clipboard. Can be str or bytes. :param encoding: same meaning as in ``subprocess.Popen``. :return: None """ args = [ self.xclip, '-selection', 'clipboard', ] if isinstance(data, bytes): if encoding is not None: warnings.warn( "encoding specified with a bytes argument. " "Encoding option will be ignored. " "To remove this warning, omit the encoding parameter or specify it as None", stacklevel=2, ) proc = subprocess.Popen( args, stdin=subprocess.PIPE, encoding=encoding, ) elif isinstance(data, str): proc = subprocess.Popen( args, stdin=subprocess.PIPE, text=True, encoding=encoding, ) else: raise TypeError(f"data argument must be of type str or bytes, not {type(data)}") stdout, stderr = proc.communicate(data) if proc.returncode != 0: raise ClipboardException( f"Copy failed. xclip returned code: {proc.returncode!r}" f"Stderr: {stderr!r}" f"Stdout: {stdout!r}" ) ``` -------------------------------- ### MacOSClip.copy Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Copies the provided content to the macOS clipboard. This method defers to the underlying backend's copy functionality. ```APIDOC ## MacOSClip.copy ### Description Copies the provided content to the macOS clipboard. ### Method `copy(*args, **kwargs)` ### Parameters Accepts arbitrary positional and keyword arguments, which are passed directly to the backend's copy method. ``` -------------------------------- ### WindowsClipboard.clear Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/win_clip.html Clears the contents of the system clipboard. ```APIDOC ## WindowsClipboard.clear ### Description Clears all content from the system clipboard, effectively making it empty. ### Method Signature `clear(self) -> None` ### Request Example ```python from pyclip import WindowsClipboard clipboard = WindowsClipboard() clipboard.clear() ``` ``` -------------------------------- ### Paste Data using pbpaste Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Retrieves data from the clipboard using the pbpaste command. Supports optional encoding, text, and errors parameters for subprocess.run. Returns binary data by default, or string if encoding/text/errors are specified. ```python args = [self.pbpaste] if encoding or text or errors: completed_proc = subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=text, encoding=encoding) else: completed_proc = subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if completed_proc.returncode != 0: raise ClipboardException(f"Copy failed. pbcopy returned code: {completed_proc.returncode!r} " f"Stderr: {completed_proc.stderr!r} " f"Stdout: {completed_proc.stdout!r}") return completed_proc.stdout ``` -------------------------------- ### Copy Data using pasteboard package Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Copies string or bytes data to the clipboard using the pasteboard package. Attempts to decode bytes to string, falling back to using PDF type if decoding fails. Ignores the encoding parameter. ```python if isinstance(data, bytes): try: data = data.decode() self.pb.set_contents(data) except UnicodeDecodeError: self.pb.set_contents(data, self._bytes_type) elif isinstance(data, str): self.pb.set_contents(data) else: raise TypeError(f"data argument must be of type str or bytes, not {type(data)}") ``` -------------------------------- ### XclipClipboard.paste Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/xclip_clip.html Retrieves data from the clipboard. The return type is binary by default. If encoding, errors, or text parameters are specified, the return type is string. ```APIDOC ## paste ### Description Retrieve data from the clipboard. ### Method `paste(encoding: str = None, text: bool = None, errors: str = None)` ### Parameters - **encoding** (str, optional) - Same meaning as in ``subprocess.run``. Defaults to None. - **text** (bool, optional) - Same meaning as in ``subprocess.run``. Defaults to None. - **errors** (str, optional) - Same meaning as in ``subprocess.run``. Defaults to None. ### Returns The clipboard contents. Return type is binary by default. If any of ``encoding``, ``errors``, or ``text`` are specified, the result type is str. ``` -------------------------------- ### paste() Source: https://pyclip.readthedocs.io/en/latest/genindex.html Retrieves and returns the text content from the clipboard. ```APIDOC ## paste() -> str ### Description Retrieves and returns the text content from the clipboard. ### Method This is a method available on clipboard objects. ### Endpoint N/A (Python function/method) ### Parameters None ### Request Example ```python import pyclip content = pyclip.paste() print(content) ``` ### Response #### Success Response (200) - **content** (str) - The text content currently in the clipboard. ``` -------------------------------- ### Conditional Wrapper for Clipboard Functions Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/__init__.html A decorator that conditionally wraps a function if a default clipboard has been successfully initialized. If the clipboard is not available, the original function is returned without modification. ```python def wrapif(f): if DEFAULT_CLIPBOARD is not None: wrapped = getattr(DEFAULT_CLIPBOARD, f.__name__) wrapper = wraps(wrapped) return wrapper(f) return f ``` -------------------------------- ### Paste from Clipboard (pyclip) Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/win_clip.html Returns clipboard contents. The return type is bytes by default, but can be a string if encoding, text, or errors parameters are provided. Handles various clipboard formats and raises specific exceptions for unparsable or non-text formats when text options are specified. ```python def paste(self, encoding: str = None, text: bool = None, errors: str = None) -> Union[str, bytes]: """ Returns clipboard contents :param encoding: same meaning as in ``bytes.encode``. Implies ``text=True`` :param text: if True, bytes object will be en :param errors: same meaning as in ``bytes.encode``. Implies ``text=True``. :return: clipboard contents. Return value is bytes by default or str if any of ``encoding``, ``text``, or ``errors`` is provided. """ with self._clipboard as clip: format = clip.EnumClipboardFormats() if format == 0: if text or encoding or errors: return '' else: return b'' if format not in _CF_FORMATS: all_formats = self._clipboard._enumerate_clipboard_formats() acceptable_formats = [f for f in all_formats if f in self._implemented_formats] if not acceptable_formats: raise UnparsableClipboardFormatException("Clipboard contents have no standard formats available. " "The contents can only be understood by a private program") if (text or encoding or errors) and format not in self._string_formats: raise ClipboardNotTextFormatException("Clipboard has no text formats available, but text options " "were specified.") format = max(acceptable_formats) d = clip.GetClipboardData(format) if format not in self._string_formats and format in self._implemented_formats: return self._handle_format(format, d) if isinstance(d, str): if format in self._string_formats: d = d.rstrip('\x00') # string formats are null-terminated if not (text or encoding or errors): return d.encode() # even though the windows API returned a string # We convert back to bytes for API consistency here return d ``` -------------------------------- ### clear() Source: https://pyclip.readthedocs.io/en/latest/genindex.html Clears the content of the clipboard. ```APIDOC ## clear() ### Description Clears the content of the clipboard. ### Method This is a method available on clipboard objects. ### Endpoint N/A (Python function/method) ### Parameters None ### Request Example ```python import pyclip pyclip.clear() ``` ### Response None ``` -------------------------------- ### Copy Data to Windows Clipboard Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/win_clip.html Copies string or bytes data to the system clipboard. For strings, CF_UNICODETEXT (13) is used. For bytes, CF_DIBV5 (11) is used. ```python with self._clipboard as clip: clip.EmptyClipboard() # we clear the clipboard to become the clipboard owner if isinstance(data, str): clip.SetClipboardText(data, 13) elif isinstance(data, bytes): data = ctypes.create_string_buffer(data) clip.SetClipboardData(11, data) else: raise TypeError(f"data must be str or bytes, not {type(data)}") ``` -------------------------------- ### ClipboardException Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/base.html Base exception class for pyclip operations. ```APIDOC ## Exception: ClipboardException ### Description Base exception class for all exceptions raised by pyclip operations. Custom exceptions inherit from this class. ``` -------------------------------- ### Clear Clipboard using pbcopy Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Clears the clipboard contents by copying an empty byte string using the pbcopy command. ```python self.copy(b'') ``` -------------------------------- ### ClipboardBase Class Source: https://pyclip.readthedocs.io/en/latest/api/base.html The abstract base class for all Clipboard implementations in pyclip. It defines the core methods that concrete clipboard classes must implement. ```APIDOC ## Class: ClipboardBase ### Description Abstract base class for Clipboard implementations. Defines the interface for clipboard operations. ### Methods #### clear() - **Description**: Clears the clipboard content. - **Abstract**: Yes #### copy(data, encoding=None) - **Description**: Copies data to the clipboard. - **Parameters**: - **data** (any) - Required - The data to be copied. - **encoding** (str) - Optional - The encoding to use for the data. - **Abstract**: Yes #### paste(encoding=None, text=None, errors=None) - **Description**: Pastes data from the clipboard. - **Parameters**: - **encoding** (str) - Optional - The encoding to use when decoding the data. - **text** (bool) - Optional - If True, return data as text. - **errors** (str) - Optional - Specifies how encoding errors are handled. - **Return Type**: Union[str, bytes] - **Abstract**: Yes ``` -------------------------------- ### paste Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/win_clip.html Retrieves the current content of the clipboard. It can return content as bytes or a string, depending on the specified parameters. ```APIDOC ## paste ### Description Returns clipboard contents. The return type is bytes by default, or str if encoding, text, or errors parameters are provided. ### Method `paste(encoding: str = None, text: bool = None, errors: str = None) -> Union[str, bytes]` ### Parameters #### Optional Parameters - **encoding** (str) - Specifies the encoding to use when converting clipboard data to a string. Implies `text=True`. - **text** (bool) - If True, ensures the clipboard data is treated as text. If not provided, the function attempts to infer the type. - **errors** (str) - Specifies how encoding errors should be handled. Implies `text=True`. ### Return Value - **Union[str, bytes]**: The content of the clipboard. Returns bytes by default, or a string if `encoding`, `text`, or `errors` are specified. ``` -------------------------------- ### Paste from Clipboard on MacOS Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Wraps the paste method of the selected backend to retrieve data from the macOS clipboard. ```python @wraps(_PasteboardBackend.paste) def paste(self, *args, **kwargs): return self.backend.paste(*args, **kwargs) ``` -------------------------------- ### MacOSClip Class Source: https://pyclip.readthedocs.io/en/latest/api/macos_clip.html The MacOSClip class provides the main interface for interacting with the MacOS clipboard. It supports clearing, copying, and pasting data. ```APIDOC ## Class: MacOSClip ### Description Provides Clipboard functionality for MacOS. Defers to one of two backends: `_PasteboardBackend` (the default) or `_PBCopyPBPasteBackend`. ### Methods #### clear() ##### Description Clear the clipboard contents. #### copy(data, encoding=None) ##### Description Copies data to the clipboard. ##### Parameters - **data** (Union[str, bytes]) – data to copy to the clipboard - **encoding** (Optional[str]) – this parameter is ignored on this backend #### paste(encoding=None, text=None, errors=None) ##### Description Retrieve contents of the clipboard. ##### Parameters - **encoding** (Optional[str]) – same meaning as in `bytes.encode`. Implies `text=True` - **text** (Optional[bool]) – if True, bytes object will be returned as str - **errors** (Optional[str]) – same meaning as in `bytes.encode`. Implies `text=True`. ##### Returns clipboard contents. Return value is bytes by default or str if any of `encoding`, `text`, or `errors` is provided. ``` -------------------------------- ### Pyclip CLI Main Function Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/cli.html Parses command-line arguments for 'copy', 'paste', and 'clear' operations and delegates to the internal _main function. Handles program exit codes. ```python # Copyright 2021 Spencer Phillip Young # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import sys def _main(args) -> int: from pyclip import copy, clear, paste if args.command == "copy": copy(sys.stdin.buffer.read()) elif args.command == 'paste': sys.stdout.buffer.write(paste()) elif args.command == 'clear': clear() else: print('Unrecognized command', file=sys.stderr) return 1 return 0 [docs] def main(): parser = argparse.ArgumentParser('pyclip') subparsers = parser.add_subparsers(title='commands', dest='command', required=True, description='Valid commands') copy_parser = subparsers.add_parser('copy', help='Copy contents from stdin to the clipboard') paste_parser = subparsers.add_parser('paste', help='Output clipboard contents to stdout') clear_parser = subparsers.add_parser('clear', help='Clear the clipboard contents') args = parser.parse_args() ret = _main(args) sys.exit(ret) ``` -------------------------------- ### MacOSClip.paste Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Retrieves content from the macOS clipboard. This method defers to the underlying backend's paste functionality. ```APIDOC ## MacOSClip.paste ### Description Retrieves content from the macOS clipboard. ### Method `paste(*args, **kwargs)` ### Parameters Accepts arbitrary positional and keyword arguments, which are passed directly to the backend's paste method. ``` -------------------------------- ### PyClip Public API Functions Source: https://pyclip.readthedocs.io/en/latest/api/index.html These are the primary functions exposed by the PyClip library for interacting with the system clipboard. They are typically imported directly from the `pyclip` package. ```python pyclip.__init__.clear(*args, **kwargs) ``` ```python pyclip.__init__.copy(*args, **kwargs) ``` ```python pyclip.__init__.paste(*args, **kwargs) ``` ```python pyclip.__init__.wrapif(f) ``` -------------------------------- ### Clipboard Exceptions Source: https://pyclip.readthedocs.io/en/latest/api/base.html Defines custom exceptions used within the pyclip base module for error handling. ```APIDOC ## Exceptions ### ClipboardException - **Description**: Base exception class for pyclip operations. ### ClipboardSetupException - **Description**: Exception raised when there is an issue setting up the clipboard. ``` -------------------------------- ### Clear Windows Clipboard Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/win_clip.html Empties the system clipboard, making the current application the owner. ```python with self._clipboard as clip: clip.EmptyClipboard() ``` -------------------------------- ### Clear Clipboard on MacOS Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Wraps the clear method of the selected backend to empty the macOS clipboard. ```python @wraps(_PasteboardBackend.clear) def clear(self): return self.backend.clear() ``` -------------------------------- ### Abstract Clipboard Base Class Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/base.html Defines the interface for clipboard operations. Implementations must provide `copy`, `paste`, and `clear` methods. ```python [docs]class ClipboardBase(ABC): """ Abstract base class for Clipboard implementations. """ [docs] @abstractmethod def copy(self, data: Union[str, bytes], encoding: str = None): return NotImplemented # pragma: no cover [docs] @abstractmethod def paste(self, encoding=None, text=None, errors=None) -> Union[str, bytes]: return NotImplemented # pragma: no cover [docs] @abstractmethod def clear(self): return NotImplemented # pragma: no cover ``` -------------------------------- ### MacOSClip.clear Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/macos_clip.html Clears the content of the macOS clipboard by calling the clear method of the underlying backend. ```APIDOC ## MacOSClip.clear ### Description Clears the content of the macOS clipboard. ### Method `clear()` ### Parameters None ``` -------------------------------- ### Clear Clipboard Contents (Python) Source: https://pyclip.readthedocs.io/en/latest/_modules/pyclip/xclip_clip.html Clears the contents of the system clipboard by copying an empty string to it. This method reuses the copy functionality. ```python def clear(self): """ Clear the clipboard contents :return: """ self.copy('') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.