threads.utils_threads

  1import os
  2import shutil
  3
  4from PyQt6.QtCore import QThread, pyqtSignal, QCoreApplication
  5
  6
  7class CopyDeleteThread(QThread):
  8    """
  9    Background worker thread for performing **file or directory copy and delete operations**
 10    without blocking the PyQt GUI.
 11
 12    This class provides an asynchronous way to execute potentially long file system tasks
 13    (copying large files, removing folders, etc.) in a background thread, while emitting
 14    progress and error signals that can be handled by the main thread safely.
 15
 16    ---
 17
 18    **Signals:**
 19
 20    - `finished (str)`: Emitted when the operation completes successfully with a message.
 21    - `error (str)`: Emitted when an error occurs, providing an error message.
 22
 23    ---
 24
 25    **Parameters:**
 26
 27    - `src` (*str*): Source file or folder path.
 28    - `dst` (*str | None*): Destination path (required for copy operations).
 29    - `is_folder` (*bool*): If `True`, the operation targets a folder instead of a file.
 30    - `copy` (*bool*): If `True`, performs a copy operation.
 31    - `delete` (*bool*): If `True`, performs a delete operation.
 32    """
 33
 34    # Signal emitted when the operation finishes successfully.
 35    finished = pyqtSignal(str)
 36    """**Signal(str):** Emitted when the operation completes successfully.  
 37    The parameter is a status message describing the result or outcome.
 38    """
 39
 40    # Signal emitted when an error occurs during execution.
 41    error = pyqtSignal(str)
 42    """**Signal(str):** Emitted when an error occurs during the operation.  
 43    The parameter contains a descriptive error message.
 44    """
 45
 46    def __init__(self, src, dst=None, is_folder=False, copy=False, delete=False):
 47        """
 48        Initialize the worker thread with operation parameters.
 49
 50        Args:
 51            src (str): Path to the source file or directory.
 52            dst (str | None): Destination path for copy operations.
 53            is_folder (bool): Whether the source represents a folder.
 54            copy (bool): Whether to perform a copy operation.
 55            delete (bool): Whether to perform a delete operation.
 56        """
 57        super().__init__()
 58        self.src = src
 59        self.dst = dst
 60        self.is_folder = is_folder
 61        self.copy = copy
 62        self.delete = delete
 63
 64    def run(self):
 65        """
 66        Executes the file system operation.
 67
 68        Depending on the configuration flags (`copy`, `delete`, `is_folder`),
 69        this method performs one or both operations:
 70        - **Copy**: Copies a file or directory from `src` to `dst`.
 71        - **Delete**: Removes a file or directory at `src`.
 72
 73        Emits:
 74            - `finished (str)`: On successful completion.
 75            - `error (str)`: On any exception during execution.
 76        """
 77        try:
 78            # --- COPY OPERATION ---
 79            if self.copy:
 80                if self.src is None or self.dst is None:
 81                    raise ValueError(QCoreApplication.translate("Threads", "Missing src or dst"))
 82
 83                if self.is_folder:
 84                    # Copy entire directory recursively
 85                    shutil.copytree(self.src, self.dst, dirs_exist_ok=True)
 86                else:
 87                    # Copy single file
 88                    shutil.copy(self.src, self.dst)
 89
 90                self.finished.emit(
 91                    QCoreApplication.translate(
 92                        "Threads",
 93                        "Successfully copied {0} to {1}"
 94                    ).format(self.src, self.dst)
 95                )
 96
 97            # --- DELETE OPERATION ---
 98            if self.delete:
 99                if self.src is None:
100                    raise ValueError(QCoreApplication.translate("Threads", "Missing src"))
101
102                if self.is_folder:
103                    # Remove entire folder tree
104                    shutil.rmtree(self.src)
105                else:
106                    # Remove single file
107                    os.remove(self.src)
108
109                self.finished.emit(
110                    QCoreApplication.translate(
111                        "Threads",
112                        "Successfully deleted {0}"
113                    ).format(self.src)
114                )
115
116        except Exception as e:
117            # Emit a formatted error message including source, destination, and exception details
118            self.error.emit(
119                QCoreApplication.translate(
120                    "Threads",
121                    "Error src:{0}, dst:{1}, {2}"
122                ).format(self.src, self.dst, e)
123            )
class CopyDeleteThread(PyQt6.QtCore.QThread):
  8class CopyDeleteThread(QThread):
  9    """
 10    Background worker thread for performing **file or directory copy and delete operations**
 11    without blocking the PyQt GUI.
 12
 13    This class provides an asynchronous way to execute potentially long file system tasks
 14    (copying large files, removing folders, etc.) in a background thread, while emitting
 15    progress and error signals that can be handled by the main thread safely.
 16
 17    ---
 18
 19    **Signals:**
 20
 21    - `finished (str)`: Emitted when the operation completes successfully with a message.
 22    - `error (str)`: Emitted when an error occurs, providing an error message.
 23
 24    ---
 25
 26    **Parameters:**
 27
 28    - `src` (*str*): Source file or folder path.
 29    - `dst` (*str | None*): Destination path (required for copy operations).
 30    - `is_folder` (*bool*): If `True`, the operation targets a folder instead of a file.
 31    - `copy` (*bool*): If `True`, performs a copy operation.
 32    - `delete` (*bool*): If `True`, performs a delete operation.
 33    """
 34
 35    # Signal emitted when the operation finishes successfully.
 36    finished = pyqtSignal(str)
 37    """**Signal(str):** Emitted when the operation completes successfully.  
 38    The parameter is a status message describing the result or outcome.
 39    """
 40
 41    # Signal emitted when an error occurs during execution.
 42    error = pyqtSignal(str)
 43    """**Signal(str):** Emitted when an error occurs during the operation.  
 44    The parameter contains a descriptive error message.
 45    """
 46
 47    def __init__(self, src, dst=None, is_folder=False, copy=False, delete=False):
 48        """
 49        Initialize the worker thread with operation parameters.
 50
 51        Args:
 52            src (str): Path to the source file or directory.
 53            dst (str | None): Destination path for copy operations.
 54            is_folder (bool): Whether the source represents a folder.
 55            copy (bool): Whether to perform a copy operation.
 56            delete (bool): Whether to perform a delete operation.
 57        """
 58        super().__init__()
 59        self.src = src
 60        self.dst = dst
 61        self.is_folder = is_folder
 62        self.copy = copy
 63        self.delete = delete
 64
 65    def run(self):
 66        """
 67        Executes the file system operation.
 68
 69        Depending on the configuration flags (`copy`, `delete`, `is_folder`),
 70        this method performs one or both operations:
 71        - **Copy**: Copies a file or directory from `src` to `dst`.
 72        - **Delete**: Removes a file or directory at `src`.
 73
 74        Emits:
 75            - `finished (str)`: On successful completion.
 76            - `error (str)`: On any exception during execution.
 77        """
 78        try:
 79            # --- COPY OPERATION ---
 80            if self.copy:
 81                if self.src is None or self.dst is None:
 82                    raise ValueError(QCoreApplication.translate("Threads", "Missing src or dst"))
 83
 84                if self.is_folder:
 85                    # Copy entire directory recursively
 86                    shutil.copytree(self.src, self.dst, dirs_exist_ok=True)
 87                else:
 88                    # Copy single file
 89                    shutil.copy(self.src, self.dst)
 90
 91                self.finished.emit(
 92                    QCoreApplication.translate(
 93                        "Threads",
 94                        "Successfully copied {0} to {1}"
 95                    ).format(self.src, self.dst)
 96                )
 97
 98            # --- DELETE OPERATION ---
 99            if self.delete:
100                if self.src is None:
101                    raise ValueError(QCoreApplication.translate("Threads", "Missing src"))
102
103                if self.is_folder:
104                    # Remove entire folder tree
105                    shutil.rmtree(self.src)
106                else:
107                    # Remove single file
108                    os.remove(self.src)
109
110                self.finished.emit(
111                    QCoreApplication.translate(
112                        "Threads",
113                        "Successfully deleted {0}"
114                    ).format(self.src)
115                )
116
117        except Exception as e:
118            # Emit a formatted error message including source, destination, and exception details
119            self.error.emit(
120                QCoreApplication.translate(
121                    "Threads",
122                    "Error src:{0}, dst:{1}, {2}"
123                ).format(self.src, self.dst, e)
124            )

Background worker thread for performing file or directory copy and delete operations without blocking the PyQt GUI.

This class provides an asynchronous way to execute potentially long file system tasks (copying large files, removing folders, etc.) in a background thread, while emitting progress and error signals that can be handled by the main thread safely.


Signals:

  • finished (str): Emitted when the operation completes successfully with a message.
  • error (str): Emitted when an error occurs, providing an error message.

Parameters:

  • src (str): Source file or folder path.
  • dst (str | None): Destination path (required for copy operations).
  • is_folder (bool): If True, the operation targets a folder instead of a file.
  • copy (bool): If True, performs a copy operation.
  • delete (bool): If True, performs a delete operation.
CopyDeleteThread(src, dst=None, is_folder=False, copy=False, delete=False)
47    def __init__(self, src, dst=None, is_folder=False, copy=False, delete=False):
48        """
49        Initialize the worker thread with operation parameters.
50
51        Args:
52            src (str): Path to the source file or directory.
53            dst (str | None): Destination path for copy operations.
54            is_folder (bool): Whether the source represents a folder.
55            copy (bool): Whether to perform a copy operation.
56            delete (bool): Whether to perform a delete operation.
57        """
58        super().__init__()
59        self.src = src
60        self.dst = dst
61        self.is_folder = is_folder
62        self.copy = copy
63        self.delete = delete

Initialize the worker thread with operation parameters.

Args: src (str): Path to the source file or directory. dst (str | None): Destination path for copy operations. is_folder (bool): Whether the source represents a folder. copy (bool): Whether to perform a copy operation. delete (bool): Whether to perform a delete operation.

def finished(unknown):

Signal(str): Emitted when the operation completes successfully.
The parameter is a status message describing the result or outcome.

def error(unknown):

Signal(str): Emitted when an error occurs during the operation.
The parameter contains a descriptive error message.

src
dst
is_folder
copy
delete
def run(self):
 65    def run(self):
 66        """
 67        Executes the file system operation.
 68
 69        Depending on the configuration flags (`copy`, `delete`, `is_folder`),
 70        this method performs one or both operations:
 71        - **Copy**: Copies a file or directory from `src` to `dst`.
 72        - **Delete**: Removes a file or directory at `src`.
 73
 74        Emits:
 75            - `finished (str)`: On successful completion.
 76            - `error (str)`: On any exception during execution.
 77        """
 78        try:
 79            # --- COPY OPERATION ---
 80            if self.copy:
 81                if self.src is None or self.dst is None:
 82                    raise ValueError(QCoreApplication.translate("Threads", "Missing src or dst"))
 83
 84                if self.is_folder:
 85                    # Copy entire directory recursively
 86                    shutil.copytree(self.src, self.dst, dirs_exist_ok=True)
 87                else:
 88                    # Copy single file
 89                    shutil.copy(self.src, self.dst)
 90
 91                self.finished.emit(
 92                    QCoreApplication.translate(
 93                        "Threads",
 94                        "Successfully copied {0} to {1}"
 95                    ).format(self.src, self.dst)
 96                )
 97
 98            # --- DELETE OPERATION ---
 99            if self.delete:
100                if self.src is None:
101                    raise ValueError(QCoreApplication.translate("Threads", "Missing src"))
102
103                if self.is_folder:
104                    # Remove entire folder tree
105                    shutil.rmtree(self.src)
106                else:
107                    # Remove single file
108                    os.remove(self.src)
109
110                self.finished.emit(
111                    QCoreApplication.translate(
112                        "Threads",
113                        "Successfully deleted {0}"
114                    ).format(self.src)
115                )
116
117        except Exception as e:
118            # Emit a formatted error message including source, destination, and exception details
119            self.error.emit(
120                QCoreApplication.translate(
121                    "Threads",
122                    "Error src:{0}, dst:{1}, {2}"
123                ).format(self.src, self.dst, e)
124            )

Executes the file system operation.

Depending on the configuration flags (copy, delete, is_folder), this method performs one or both operations:

  • Copy: Copies a file or directory from src to dst.
  • Delete: Removes a file or directory at src.

Emits: - finished (str): On successful completion. - error (str): On any exception during execution.