### Install PyGObject Dependencies Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_gio.md Provides package installation commands for Debian/Ubuntu, Fedora/RHEL, and Arch Linux to set up PyGObject and GIO. ```bash # Debian/Ubuntu sudo apt-get install python3-gi gir1.2-gio-2.0 # Fedora/RHEL sudo dnf install python3-gobject gio # Arch sudo pacman -S python-gobject glib2 # Or via pip on some systems pip install PyGObject ``` -------------------------------- ### Install send2trash with Native Libraries Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/mac.md Use this command to install send2trash with the necessary native libraries for macOS, or install PyObjC separately. ```bash pip install send2trash[nativelib] # or pip install pyobjc>=9.0 ``` -------------------------------- ### Create a Virtual Environment Source: https://github.com/arsenetar/send2trash/blob/master/README.rst Create and activate a virtual environment for package installation, especially on systems enforcing PEP 668. ```bash python -m venv .venv GNU/Linux / macOS: source .venv/bin/activate Windows: .venv\Scripts\activate ``` -------------------------------- ### PostDeleteItem Implementation Example Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md An example implementation of PostDeleteItem that captures the display name (path) of the item if it was successfully moved to the Recycle Bin. ```python def PostDeleteItem(self, flags, item, hr_delete, newly_created): if newly_created: # Store the path of the item in the Recycle Bin self.newItem = newly_created.GetDisplayName(shellcon.SHGDN_FORPARSING) ``` -------------------------------- ### Install Send2Trash Source: https://github.com/arsenetar/send2trash/blob/master/README.rst Install the Send2Trash package using pip. For native library support on specific platforms, use the 'nativeLib' extra. ```bash python -m pip install -U send2trash ``` ```bash python -m pip install -U send2trash[nativeLib] ``` ```bash python -m pip install -e . ``` -------------------------------- ### Example: Handling OSError from COM Error Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/errors.md Illustrates catching an OSError that originates from a COM error on Windows, and accessing the original HRESULT. ```python from send2trash import send2trash try: send2trash('/protected/file.txt') except OSError as e: # COM error converted to OSError print(f"Error: {e}") # Check original HRESULT via args if len(e.args) > 3: hresult = e.args[3] print(f"HRESULT: {hex(hresult)}") ``` -------------------------------- ### Install PyGObject for Linux Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Install PyGObject to enable the GIO implementation for send2trash on Linux systems with GTK/GNOME. This provides a more integrated experience. ```bash pip install PyGObject ``` -------------------------------- ### Install send2trash with Native Library Support Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Install send2trash with optional native library support for enhanced features on Windows and macOS. This is recommended for modern OS versions. ```bash pip install send2trash[nativelib] ``` -------------------------------- ### Example Usage of send2trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/mac.md Demonstrates direct usage of the legacy send2trash function with string and bytes paths. ```python from send2trash.mac.legacy import send2trash # Direct use of legacy implementation (normally selected automatically) send2trash('/Users/user/file.txt') # Using bytes send2trash(b'/Users/user/file.txt') ``` -------------------------------- ### PreDeleteItem Implementation Example Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md An example implementation of PreDeleteItem. It checks if the recycle flag is set to determine whether to proceed with deletion. Note: The provided implementation always returns 0, allowing deletion to proceed. ```python def PreDeleteItem(self, flags, item): # Only proceed if TSF_DELETE_RECYCLE_IF_POSSIBLE is set if flags & shellcon.TSF_DELETE_RECYCLE_IF_POSSIBLE: return 0 # S_OK - proceed else: return 0x80004005 # E_FAIL - abort (but also returns 0) ``` -------------------------------- ### Send2trash Usage Examples Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Demonstrates various ways to call the send2trash function with different path types and quantities. Ensure correct path types are used for reliable operation. ```python send2trash('/path/to/file.txt') ``` ```python send2trash(b'/path/to/file.txt') ``` ```python send2trash(Path('/path/to/file.txt')) ``` ```python send2trash(['/file1.txt', '/file2.txt']) ``` ```python send2trash(['/file.txt', b'/file.txt', Path('/file.txt')]) ``` -------------------------------- ### Send2Trash Platform-Specific Entry Points Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/util.md These examples show how the preprocess_paths function is integrated into the send2trash function across different platform implementations (macOS legacy, Windows modern, GIO, and other platforms). ```python # From send2trash/mac/legacy.py def send2trash(paths): paths = preprocess_paths(paths) # ... rest of implementation ``` ```python # From send2trash/win/modern.py def send2trash(paths): paths = preprocess_paths(paths) # ... rest of implementation ``` ```python # From send2trash/plat_gio.py def send2trash(paths): paths = preprocess_paths(paths) # ... rest of implementation ``` ```python # From send2trash/plat_other.py def send2trash(paths): paths = preprocess_paths(paths) # ... rest of implementation ``` -------------------------------- ### Export XDG_DATA_HOME Environment Variable Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Example of setting the XDG_DATA_HOME environment variable to specify a custom location for the home trash directory on Linux/Freedesktop systems. ```bash export XDG_DATA_HOME=/custom/location ``` -------------------------------- ### Python Send2Trash Error Handling Examples Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/errors.md Demonstrates catching FileNotFoundError for non-existent files and successful trashing of existing files and pathlib.Path objects. Ensure necessary imports are present. ```python import tempfile import os from pathlib import Path from send2trash import send2trash, TrashPermissionError # Test file not found try: send2trash('/nonexistent/file.txt') except FileNotFoundError: print("✓ FileNotFoundError caught") # Test with existing file with tempfile.NamedTemporaryFile(delete=False) as f: temp_path = f.name try: send2trash(temp_path) print("✓ File trashed successfully") except Exception as e: print(f"✗ Unexpected error: {e}") # Test with pathlib.Path test_file = Path(tempfile.gettempdir()) / "test_file.txt" test_file.write_text("test") try: send2trash(test_file) print("✓ Pathlib.Path trashed successfully") except Exception as e: print(f"✗ Unexpected error: {e}") ``` -------------------------------- ### Example: Catching TypeError for Invalid Path Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/errors.md Demonstrates how to catch a TypeError when an invalid path type (like None) is included in the list of paths to be trashed. ```python from send2trash import send2trash try: send2trash(['/file.txt', None]) # None is not a valid path except TypeError as e: print(f"Invalid path type: {e}") ``` -------------------------------- ### Send to Recycle Bin (Modern Implementation) Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/windows.md Use this function to move files or directories to the Recycle Bin on Windows Vista and later, provided pywin32 is installed. It handles single paths, multiple paths, and UNC paths. ```python from send2trash import send2trash # On Windows Vista+ with pywin32 installed send2trash('C:\\Users\\User\\old_file.txt') # Multiple files send2trash([ 'C:\\Users\\User\\Downloads\\file1.zip', 'C:\\Users\\User\\Downloads\\file2.pdf' ]) # UNC paths work send2trash('\\server\\share\\file.txt') ``` -------------------------------- ### Exception Handling with Logging Integration Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/errors.md This example shows how to integrate send2trash exception handling with Python's logging module to record warnings and errors, including traceback information for debugging. ```python import logging from send2trash import send2trash, TrashPermissionError logger = logging.getLogger(__name__) try: send2trash(path) except TrashPermissionError as e: logger.warning(f"Cannot trash: {e.filename}", exc_info=True) except OSError as e: logger.error(f"Failed to trash: {e}", exc_info=True) ``` -------------------------------- ### Illustrate Collections Types for Paths Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Shows examples of different iterable collections that can be used to pass multiple paths to send2trash. Supports lists, tuples, sets, and generators yielding path-like objects. ```python from typing import Iterable # Any iterable of paths paths_iterable: Iterable[Union[str, bytes, PathLike]] # Examples: list[str] # List of strings tuple[str, ...] # Tuple of strings set[pathlib.Path] # Set of Path objects generator of str # Generator yielding strings ``` -------------------------------- ### Get Short Path Name for Long Path Handling Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/windows.md Converts a long Windows path to its 8.3 short path format to work around path length limitations in older APIs. ```python def get_short_path_name(long_name: str) -> str: """Convert to 8.3 format to work around path length limits""" ``` -------------------------------- ### Create and Use a Custom Sink Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md Demonstrates how to create a custom sink and check for items moved to the Recycle Bin after a file operation. ```python from send2trash.win.IFileOperationProgressSink import create_sink, FileOperationProgressSink # Create custom sink sink = FileOperationProgressSink() sink._wrap_(sink) # Check what was moved to Recycle Bin # (after IFileOperation.PerformOperations()) if sink.newItem: print(f"Item in Recycle Bin: {sink.newItem}") ``` -------------------------------- ### Create and Use Progress Sink Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md Demonstrates how to create a progress sink object using the create_sink factory function and then use it with IFileOperation for file deletion. ```python from send2trash.win.IFileOperationProgressSink import create_sink # Create a progress sink sink = create_sink() # Use with IFileOperation fileop.DeleteItem(item, sink) fileop.PerformOperations() ``` -------------------------------- ### Instantiate FileOperationProgressSink Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md Illustrates how to instantiate the FileOperationProgressSink class. Note that direct instantiation is generally not recommended; use the create_sink() factory function instead. ```python sink = FileOperationProgressSink() # Typically not called directly; use create_sink() instead ``` -------------------------------- ### COM Resource Management in Python Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/windows.md Shows the correct way to initialize and uninitialize the COM library for use with Windows operations in Python. This ensures proper cleanup of COM resources. ```python pythoncom.CoInitialize() # Initialize COM try: # Perform operations finally: pythoncom.CoUninitialize() # Always cleanup ``` -------------------------------- ### COM Wrapper Initialization Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md Shows the `_wrap_()` method used in the constructor to register a Python object as a COM object, enabling Windows COM to interact with it. ```python def __init__(self): self._wrap_(self) # Register Python object as COM object self.newItem = None ``` -------------------------------- ### Flexible Path Input Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Demonstrates how to use the `trash_files` function to send files to the trash, accepting a flexible range of path inputs including strings, bytes, and PathLike objects, individually or as a sequence. ```APIDOC ## trash_files ### Description Accepts flexible path input for sending files to the trash. ### Parameters - **paths** (Union[str, bytes, os.PathLike, Sequence[Union[str, bytes, os.PathLike]]]) - Required - A single path or a sequence of paths to be trashed. ### Returns None ``` -------------------------------- ### Send pathlib.Path to Trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Demonstrates how to send a single `pathlib.Path` object to the trash. Ensure `pathlib` is imported. ```python from pathlib import Path # Send a pathlib.Path to trash path = Path.home() / "Documents" / "old_file.txt" send2trash(path) ``` -------------------------------- ### Send2Trash with UNC Paths Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/windows.md Demonstrates how to use send2trash with both server/share and IP address-based UNC paths. ```python send2trash('\\server\share\file.txt') send2trash('\\192.168.1.100\shared\document.docx') ``` -------------------------------- ### Progress Sink Initialization Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/windows.md This snippet illustrates how to create and use a custom IFileOperationProgressSink for tracking operations in the modern send2trash implementation. ```python from send2trash.win.IFileOperationProgressSink import create_sink sink = create_sink() fileop.DeleteItem(item, sink) ``` -------------------------------- ### Ensure Directory Creation Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Ensures a directory exists, creating it with secure permissions (0o700) if it does not. Parent directories are created as needed. ```python from send2trash.plat_other import check_create check_create('/home/user/.local/share/Trash/files') ``` -------------------------------- ### check_create Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Ensures a directory exists, creating it with secure permissions (mode 0o700) if it does not. It also creates any necessary parent directories. ```APIDOC ## check_create ### Description Ensures a directory exists, creating it with mode 0o700 if needed. Parent directories are created as necessary. ### Method N/A (Python function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from send2trash.plat_other import check_create check_create('/home/user/.local/share/Trash/files') ``` ### Response #### Success Response This function does not return a value upon success. #### Response Example N/A ``` -------------------------------- ### Send Standard pathlib.Path to Trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Uses the standard `pathlib.Path` for cross-platform compatibility when sending a file to trash. Requires importing `Path` from `pathlib`. ```python from pathlib import Path from send2trash import send2trash # Standard cross-platform p1 = Path('/home/user/file.txt') send2trash(p1) ``` -------------------------------- ### Integrating IFileOperationProgressSink for Deletion Monitoring Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md Demonstrates how to create and use an `IFileOperationProgressSink` to monitor file deletion operations using pywin32. This involves creating a file operation object, registering the sink, adding items for deletion, and performing the operations. ```python from send2trash.win.IFileOperationProgressSink import create_sink from win32com.shell import shell import pythoncom # Create file operation object fileop = pythoncom.CoCreateInstance( shell.CLSID_FileOperation, None, pythoncom.CLSCTX_ALL, shell.IID_IFileOperation, ) # Create and register progress sink sink = create_sink() # Register items for deletion for path in paths: item = shell.SHCreateItemFromParsingName(path, None, shell.IID_IShellItem) fileop.DeleteItem(item, sink) # Perform all operations fileop.PerformOperations() ``` -------------------------------- ### Python: Handle Trash Permission Error (External Volume) Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Illustrates handling TrashPermissionError on Linux/BSD when unable to trash files on an external volume. Provides options for deletion or moving to home trash. ```python try: send2trash('/media/external/file.txt') except TrashPermissionError: # Cannot trash on this external volume # Application may: # 1. Permanently delete file # 2. Move to home trash # 3. Prompt user for action import os try: os.remove('/media/external/file.txt') except OSError: print("Cannot delete either") ``` -------------------------------- ### Send Multiple pathlib.Path Objects to Trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Shows how to send a list of `pathlib.Path` objects to the trash. This is useful for batch operations. ```python from pathlib import Path # Multiple Path objects paths = [Path.home() / f"file{i}.txt" for i in range(5)] send2trash(paths) ``` -------------------------------- ### Handle External Volume Trash Permissions Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Demonstrates how to handle potential TrashPermissionError when attempting to trash a file on an external volume, which may occur if the trash directory cannot be created. ```python # Handle permission errors on external volumes try: send2trash('/media/usb_drive/video.mp4') except TrashPermissionError: print("Cannot trash file on external volume") ``` -------------------------------- ### Python: Handle Permission Denied Error (File) Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Shows how to handle a PermissionError when trying to trash a file that the current user does not have permission to access. This might require elevated privileges. ```python try: send2trash('/root/private_file.txt') except PermissionError: # No permission to access file # May need elevated privileges pass ``` -------------------------------- ### Send2Trash CLI Usage Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Demonstrates how to use the send2trash command-line tool to move files and directories to the trash. Supports single or multiple files and a verbose output option. ```bash send2trash [options] [ ...] Options: -v, --verbose Print deleted files -h, --help Show help message ``` ```bash # Single file send2trash /path/to/file.txt # Multiple files send2trash file1.txt file2.txt dir/ # Verbose mode send2trash -v /path/to/file.txt # Output: Trashed «/path/to/file.txt» ``` -------------------------------- ### IFileOperationProgressSink Methods Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md Lists the methods required by the IFileOperationProgressSink interface. These methods are called by Windows during file operations. Default implementations have no-op behavior. ```python _public_methods_ = [ "StartOperations", # Called when operation begins "FinishOperations", # Called when operation completes "PreRenameItem", # Before rename (not used for delete) "PostRenameItem", # After rename "PreMoveItem", # Before move (not used for delete) "PostMoveItem", # After move "PreCopyItem", # Before copy (not used for delete) "PostCopyItem", # After copy "PreDeleteItem", # Before delete (implemented) "PostDeleteItem", # After delete (implemented) "PreNewItem", # Before new item creation "PostNewItem", # After new item creation "UpdateProgress", # Progress update callback "ResetTimer", # Reset progress timer "PauseTimer", # Pause progress timer "ResumeTimer", # Resume progress timer ] ``` -------------------------------- ### Python: Handle File Not Found Error Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Demonstrates how to catch a FileNotFoundError when attempting to trash a file that no longer exists. This is useful to prevent unnecessary operations. ```python try: send2trash('/nonexistent/file.txt') except FileNotFoundError: # File already gone, operation not needed pass ``` -------------------------------- ### Send to Trash with Error Handling Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_gio.md Demonstrates how to use send2trash and catch specific GIO errors like TrashPermissionError and general OSErrors. ```python from send2trash import send2trash, TrashPermissionError try: send2trash('/media/external_drive/file.txt') except TrashPermissionError: # Cannot trash on this external volume - no trash directory available print("Cannot trash on this device") except OSError as e: # Other GIO/filesystem errors print(f"Error: {e}") ``` -------------------------------- ### Flexible Path Input for Trash Files Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Accepts various path formats including strings, bytes, PathLike objects, or sequences of these. Ensure the input is compatible with send2trash. ```python from typing import Sequence, Union from pathlib import Path import os # Accept flexible path input def trash_files(paths: Union[str, bytes, os.PathLike, Sequence[Union[str, bytes, os.PathLike]]]) -> None: from send2trash import send2trash send2trash(paths) ``` -------------------------------- ### info_for Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Generates the content of a `.trashinfo` metadata file for a trashed item. This includes the original path and the deletion timestamp, formatted in INI style. ```APIDOC ## info_for ### Description Generates the content of a `.trashinfo` metadata file for a trashed item. This includes the original path and the deletion timestamp, formatted in INI style. ### Method `info_for` (Python function) ### Parameters #### Path Parameters - `src` (str or bytes) - Required - Original path of the file being trashed - `topdir` (str, bytes, or None) - Optional - Top-level directory (None for absolute path, value for relative path computation) ### Return Value String containing INI-format metadata with `[Trash Info]` section. ### Format ``` [Trash Info] Path= DeletionDate=YYYY-MM-DDTHH:MM:SS ``` ### Behavior - Uses URL encoding (`urllib.parse.quote`) for the Path value - Includes timestamp at time of trashing - If `topdir` is provided and file is under it, uses relative path - Otherwise uses absolute path ### Request Example ```python from send2trash.plat_other import info_for info = info_for('/home/user/document.txt', None) print(info) info = info_for('/media/usb/file.txt', '/media/usb') print(info) ``` ``` -------------------------------- ### Type-Checked File Processing with send2trash (Python) Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Demonstrates how to use send2trash with type checkers for lists of strings, single strings, and pathlib.Path objects. Ensures type safety in file operations. ```python from send2trash import send2trash from pathlib import Path # Type-checked code def process_files(file_paths: list[str]) -> None: send2trash(file_paths) def process_single_file(file_path: str) -> None: send2trash(file_path) def process_paths(paths: list[Path]) -> None: send2trash(paths) ``` -------------------------------- ### Module Routing Logic Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/windows.md This code snippet demonstrates the logic used to select the appropriate send2trash implementation based on the Windows version and pywin32 availability. ```python if int(version().split(".", 1)[0]) >= 6: # Vista or newer (version 6+) try: from send2trash.win.modern import send2trash except ImportError: from send2trash.win.legacy import send2trash else: from send2trash.win.legacy import send2trash ``` -------------------------------- ### Import send2trash GIO Implementation Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_gio.md This code snippet shows how the send2trash library attempts to import the GIO implementation first, falling back to plat_other if GIO is not available. This is the primary logic for selecting the GIO backend. ```python # From send2trash/__init__.py try: from send2trash.plat_gio import send2trash except ImportError: from send2trash.plat_other import send2trash ``` -------------------------------- ### GIO File Trash API Usage Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_gio.md Shows how to use the Gio.File.trash() method to send a file to the system trash. The cancellable=None argument indicates the operation cannot be cancelled. ```python from gi.repository import Gio, GLib # Create file object from path f = Gio.File.new_for_path(path) # Move to trash f.trash(cancellable=None) ``` -------------------------------- ### Send Explicit POSIX Path to Trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Demonstrates sending an explicit POSIX path using `PurePosixPath` to the trash. The path is automatically converted to a string via `os.fspath()`. ```python from pathlib import Path, PurePosixPath from send2trash import send2trash # Explicit POSIX path p2 = PurePosixPath('/home/user/file.txt') send2trash(p2) # Converted to str by os.fspath() ``` -------------------------------- ### Send a Single File to Trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/send2trash.md Use this snippet to move a single file to the system trash. Ensure the file path is correct. ```python from send2trash import send2trash # Send a single file to trash send2trash('/path/to/file.txt') ``` -------------------------------- ### Callback Pattern for Trashing Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Shows the `trash_with_callback` function, which allows executing a callback function upon successful trashing of a file. ```APIDOC ## trash_with_callback ### Description Enables a callback function to be executed after a file is successfully trashed. ### Parameters - **path** (str) - Required - The path of the file to trash. - **on_success** (Callable[[], None]) - Required - A function to call upon successful trashing. ### Returns None ### Error Handling Catches `OSError` and prints an error message. ``` -------------------------------- ### find_ext_volume_trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Locates or creates the trash directory for an external volume, following the Freedesktop specification. It attempts to use existing `.Trash/$UID` directories and falls back to creating `.Trash-$UID` if necessary. ```APIDOC ## find_ext_volume_trash ### Description Locates or creates the trash directory for an external volume, following the Freedesktop specification. It attempts to use existing `.Trash/$UID` directories and falls back to creating `.Trash-$UID` if necessary. ### Method `find_ext_volume_trash` (Python function) ### Parameters #### Path Parameters - `volume_root` (bytes or str) - Required - Root directory of the external volume/mount point ### Return Value Path to the trash directory (str or bytes, matches input type). ### Behavior 1. First attempts to use `.Trash/$UID` directory if it exists with proper permissions 2. Falls back to creating `.Trash-$UID` directory 3. Raises `TrashPermissionError` if unable to create `.Trash-$UID` (permission denied) ### Request Example ```python from send2trash.plat_other import find_ext_volume_trash trash_dir = find_ext_volume_trash('/media/usb_drive') print(f"Using trash: {trash_dir}") ``` ``` -------------------------------- ### Module Routing Logic Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/mac.md This Python code demonstrates the logic used to select the appropriate send2trash implementation based on Python version and macOS version. ```python if version_info >= (3, 6) and macos_ver >= (10, 9): try: from send2trash.mac.modern import send2trash except ImportError: from send2trash.mac.legacy import send2trash else: from send2trash.mac.legacy import send2trash ``` -------------------------------- ### Send2Trash Filesystem Structure Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Illustrates the directory structure created by send2trash for managing trashed files and their metadata. ```text ~/.local/share/Trash/ ├── files/ # Actual trashed file contents │ ├── document.txt │ └── old_config 1 └── info/ # Metadata files ├── document.txt.trashinfo └── old_config 1.trashinfo /media/usb/.Trash-1000/ # External volume trash (fallback) ├── files/ └── info/ ``` -------------------------------- ### send2trash Function (Modern Implementation) Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/windows.md Moves files or directories to the Recycle Bin using the Windows IFileOperation COM interface. This is the primary function for users on Windows Vista and later when pywin32 is available. ```APIDOC ## send2trash Function (Modern Implementation) ### Description Moves files or directories to the Recycle Bin using the Windows IFileOperation COM interface. This function is used on Windows Vista and later systems when the `pywin32` library is installed. ### Method `send2trash(paths: str | bytes | PathLike | Iterable[str | bytes | PathLike]) -> None` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **paths** (str, bytes, PathLike, or Iterable) - Required - File or directory paths to move to Recycle Bin. ### Request Example ```python from send2trash import send2trash # Single file send2trash('C:\Users\User\old_file.txt') # Multiple files send2trash([ 'C:\Users\User\Downloads\file1.zip', 'C:\Users\User\Downloads\file2.pdf' ]) # UNC paths send2trash('\\server\share\file.txt') ``` ### Response #### Success Response Returns `None` upon successful execution. #### Response Example ```python # No explicit return value on success ``` ### Error Handling * **`OSError`**: Raised for file not found, permission denied, or other filesystem/COM errors. * **`pywintypes.com_error`**: COM errors are caught and re-raised as `OSError`, including the HRESULT error code for debugging. ``` -------------------------------- ### Exception Handling with Fallback Mechanisms Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/errors.md This snippet illustrates how to implement fallback strategies when send2trash fails, such as moving the file to the user's home trash directory or, as a final resort, permanently deleting the file. ```python import os from send2trash import send2trash, TrashPermissionError try: send2trash(path) except TrashPermissionError: # Fallback: move to home trash if possible import shutil try: home_trash = os.path.expanduser('~/.local/share/Trash/files') shutil.move(path, home_trash) except Exception: # Final fallback: delete permanently os.remove(path) except OSError as e: print(f"Error: {e}") ``` -------------------------------- ### Exception Handling with send2trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Provides guidance on catching exceptions raised by `send2trash`, including specific exceptions like `TrashPermissionError` and general `OSError`. ```APIDOC ## Exception Handling ### Description Demonstrates how to handle exceptions raised by the `send2trash` function. ### Exception Hierarchy All exceptions inherit from `OSError` or its subclasses. ### Catching Exceptions ```python from send2trash import send2trash, TrashPermissionError try: send2trash(path) except TrashPermissionError: # Specific to trash operation on external volumes (Linux) pass except PermissionError: # Regular permission denied (broader) pass except OSError: # All filesystem/system errors pass except Exception: # Catch everything (generally not recommended) pass ``` ``` -------------------------------- ### Send File to Trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Moves a single file to the trash. If the file is on the same device as the home directory, it uses the home trash location. Otherwise, it attempts to use the trash directory on the external volume. ```python from send2trash import send2trash # Send file to trash (uses home trash if on same device) send2trash('/home/user/document.txt') ``` -------------------------------- ### Determine Mount Point for a Path Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Determines the mount point (root of filesystem) for a given path. This is helpful for understanding filesystem boundaries when dealing with file operations. ```python from send2trash.plat_other import find_mount_point # Find mount point for a file mount = find_mount_point('/media/usb/file.txt') print(f"Mount point: {mount}") # Output: /media/usb ``` -------------------------------- ### Generate .trashinfo Metadata Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Generates the content of a .trashinfo metadata file for a trashed item. This includes the original path and deletion date, formatted as INI. ```python from send2trash.plat_other import info_for # Generate metadata for home trash info = info_for('/home/user/document.txt', None) print(info) # Output: [Trash Info]\nPath=%2Fhome%2Fuser%2Fdocument.txt\nDeletionDate=2024-03-15T14:30:45\n # Generate metadata with relative path info = info_for('/media/usb/file.txt', '/media/usb') print(info) # Output: [Trash Info]\nPath=file.txt\nDeletionDate=2024-03-15T14:30:45\n ``` -------------------------------- ### Callback Pattern for Trashing with Success Notification Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Trashes a file and executes a success callback function upon successful completion. Includes basic error handling for OSError. ```python from typing import Callable # Callback pattern def trash_with_callback(path: str, on_success: Callable[[], None]) -> None: from send2trash import send2trash try: send2trash(path) on_success() except OSError as e: print(f"Error: {e}") ``` -------------------------------- ### Convert Paths using os.fspath Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/util.md This function converts all provided paths to their string representation using os.fspath(). This ensures compatibility with various path-like objects, including pathlib.Path instances. ```python return [os.fspath(path) for path in paths] ``` -------------------------------- ### Trash Multiple Files Source: https://github.com/arsenetar/send2trash/blob/master/README.rst Use the send2trash function to move multiple files to the trash by passing a list of file paths. ```python from send2trash import send2trash send2trash(['some_file1', 'some_file2']) ``` -------------------------------- ### Base Class for COM Objects Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md Shows the import for the base class `DesignatedWrapPolicy` from pywin32, which manages COM object lifetime and registration. ```python from win32com.server.policy import DesignatedWrapPolicy ``` -------------------------------- ### Import send2trash Function Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Import the main send2trash function from the library. This is the primary way to use the library's functionality. ```python from send2trash import send2trash ``` -------------------------------- ### Send Files to Trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/README.md Use the `send2trash()` function to move single files, multiple files, or PathLike objects to the system trash. Ensure the `send2trash` library is imported. ```python from send2trash import send2trash # Single file send2trash('/path/to/file.txt') # Multiple files send2trash(['/path/to/file1.txt', '/path/to/file2.txt']) # PathLike objects (pathlib.Path) from pathlib import Path send2trash(Path.home() / 'Documents' / 'old_file.txt') ``` -------------------------------- ### Basic Exception Handling with send2trash Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/errors.md This snippet shows the basic pattern for catching common exceptions like TrashPermissionError, PermissionError, FileNotFoundError, and other OS errors when using send2trash. ```python from send2trash import send2trash, TrashPermissionError try: send2trash(path) except TrashPermissionError: print("Cannot trash on this device") except PermissionError: print("Permission denied") except FileNotFoundError: print("File not found") except OSError as e: print(f"Other error: {e}") ``` -------------------------------- ### Determine Long-Path Prefix and Path Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/windows.md Identifies the appropriate long-path prefix (e.g., \\?\) and constructs the prefixed path for Windows API calls. ```python def prefix_and_path(path: str) -> tuple[str, str]: """Determine long-path prefix and create prefixed path""" ``` -------------------------------- ### Platform-Specific Send2Trash Imports Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Demonstrates importing the send2trash function from platform-specific modules. All these implementations return None. ```python # All of these have the same signature from send2trash.mac import send2trash # macOS: None from send2trash.win import send2trash # Windows: None from send2trash.plat_gio import send2trash # GIO: None from send2trash.plat_other import send2trash # Freedesktop: None ``` -------------------------------- ### Handle Trash Errors Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/START_HERE.md Implement try-except blocks to gracefully handle potential errors during the trash operation, such as permission issues or other OS-level errors. ```python try: send2trash(path) except TrashPermissionError: # Handle external volume issue except OSError: # Handle other errors ``` -------------------------------- ### Handle TrashPermissionError in Python Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Demonstrates how to catch `TrashPermissionError` when using `send2trash`. This allows for specific handling of permission issues related to trashing files, potentially falling back to permanent deletion. ```python from send2trash import send2trash, TrashPermissionError try: send2trash('/media/external/file.txt') except TrashPermissionError as e: print(f"Cannot trash: {e.filename}") # May choose to permanently delete instead except OSError as e: print(f"Other error: {e}") ``` -------------------------------- ### GIO Error Handling Flow Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_gio.md Illustrates the error handling logic for Gio.File.trash(), mapping GLib.Error to specific Python exceptions like TrashPermissionError or OSError. ```python try: Gio.File.trash() except GLib.Error as e: if e.code == Gio.IOErrorEnum.NOT_SUPPORTED: raise TrashPermissionError(message) else: raise OSError(e.message) ``` -------------------------------- ### FileOperationProgressSink Class Definition Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/IFileOperationProgressSink.md Shows the class definition for FileOperationProgressSink, highlighting its COM interface and public methods. This class is used to monitor file operations. ```python class FileOperationProgressSink(DesignatedWrapPolicy): _com_interfaces_ = [shell.IID_IFileOperationProgressSink] _public_methods_ = [...] ``` -------------------------------- ### Move File to Trash (Platform-Specific) Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/plat_other.md Moves a single file to the trash directory, handling filename collisions and metadata. Use this for direct file trashing operations. ```python from send2trash.plat_other import trash_move import os # Move file to trash (home trash) trash_move(b'/home/user/file.txt', b'/home/user/.local/share/Trash') # Move with explicit topdir (for relative path in metadata) trash_move(b'/media/usb/file.txt', b'/media/usb/.Trash-1000', b'/media/usb') ``` -------------------------------- ### Generator Pattern for Trashing Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/types.md Illustrates the `trash_many` function, which efficiently handles trashing multiple files by accepting an iterable (like a generator) of file paths. ```APIDOC ## trash_many ### Description Supports a generator pattern for trashing multiple files efficiently. ### Parameters - **file_generator** (Iterable[Union[str, Path]]) - Required - An iterable yielding paths to be trashed. ### Returns None ``` -------------------------------- ### Send2trash Function (Legacy Windows) Source: https://github.com/arsenetar/send2trash/blob/master/_autodocs/api-reference/windows.md Moves files to the Recycle Bin using the Windows SHFileOperation shell API. Handles direct paths and automatically manages long path names. ```python from send2trash.win.legacy import send2trash # Direct use of legacy implementation send2trash('C:\\Users\\User\\file.txt') # Handles long path names automatically send2trash('C:\\very\\long\\path\\that\\exceeds\\max\\length\\file.txt') ```