nano-dev-utils 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of nano-dev-utils might be problematic. Click here for more details.

@@ -0,0 +1,14 @@
1
+ """Nano-Utils-Yaronday - A collection of small Python utilities for developers.
2
+ Copyright (c) 2025 Yaron Dayan
3
+ """
4
+ from .dynamic_importer import Importer
5
+ from .timers import Timer
6
+ from .release_ports import PortsRelease, PROXY_SERVER, INSPECTOR_CLIENT
7
+
8
+ __all__ = [
9
+ "Importer",
10
+ "Timer",
11
+ "PortsRelease",
12
+ "PROXY_SERVER",
13
+ "INSPECTOR_CLIENT",
14
+ ]
@@ -0,0 +1,28 @@
1
+ from types import ModuleType
2
+ from typing import Any
3
+
4
+ import importlib
5
+
6
+
7
+ class Importer:
8
+ def __init__(self):
9
+ self.imported_modules = {}
10
+
11
+ def import_mod_from_lib(self, library: str, module_name: str) -> ModuleType | Any:
12
+ """Lazily imports and caches a specific submodule from a given library.
13
+ :param library: The name of the library.
14
+ :param module_name: The name of the module to import.
15
+ :return: The imported module.
16
+ """
17
+ if module_name in self.imported_modules:
18
+ return self.imported_modules[module_name]
19
+
20
+ try:
21
+ module = importlib.import_module(f"{library}.{module_name}")
22
+ self.imported_modules[module_name] = module
23
+ return module
24
+ except ModuleNotFoundError as e:
25
+ raise ImportError(f"Could not import {library}.{module_name}") from e
26
+
27
+
28
+
@@ -0,0 +1,156 @@
1
+ import platform
2
+ import subprocess
3
+ import logging
4
+ from typing import Optional
5
+
6
+
7
+ logging.basicConfig(filename='port release.log',
8
+ level=logging.INFO,
9
+ format='%(asctime)s - %(levelname)s: %(message)s',
10
+ datefmt='%d-%m-%Y %H:%M:%S')
11
+ lgr = logging.getLogger(__name__)
12
+
13
+ PROXY_SERVER = 6277
14
+ INSPECTOR_CLIENT = 6274
15
+
16
+
17
+ class PortsRelease:
18
+ def __init__(self, default_ports: Optional[list[int]] = None):
19
+ self.default_ports: list[int] = default_ports \
20
+ if default_ports is not None else [PROXY_SERVER, INSPECTOR_CLIENT]
21
+
22
+ @staticmethod
23
+ def _log_process_found(port: int, pid: int) -> str:
24
+ return f'Process ID (PID) found for port {port}: {pid}.'
25
+
26
+ @staticmethod
27
+ def _log_process_terminated(pid: int, port: int) -> str:
28
+ return f'Process {pid} (on port {port}) terminated successfully.'
29
+
30
+ @staticmethod
31
+ def _log_no_process(port: int) -> str:
32
+ return f'No process found listening on port {port}.'
33
+
34
+ @staticmethod
35
+ def _log_invalid_port(port: int) -> str:
36
+ return f'Invalid port number: {port}. Skipping.'
37
+
38
+ @staticmethod
39
+ def _log_terminate_failed(pid: int, port: Optional[int] = None,
40
+ error: Optional[str] = None) -> str:
41
+ base_msg = f'Failed to terminate process {pid}'
42
+ if port:
43
+ base_msg += f' (on port {port})'
44
+ if error:
45
+ base_msg += f'. Error: {error}'
46
+ return base_msg
47
+
48
+ @staticmethod
49
+ def _log_line_parse_failed(line: str) -> str:
50
+ return f'Could not parse PID from line: {line}'
51
+
52
+ @staticmethod
53
+ def _log_unexpected_error(e: Exception) -> str:
54
+ return f'An unexpected error occurred: {e}'
55
+
56
+ @staticmethod
57
+ def _log_cmd_error(error: bytes) -> str:
58
+ return f'Error running command: {error.decode()}'
59
+
60
+ @staticmethod
61
+ def _log_unsupported_os() -> str:
62
+ return f'Unsupported OS: {platform.system()}'
63
+
64
+ def get_pid_by_port(self, port: int) -> Optional[int]:
65
+ """Gets the process ID (PID) listening on the specified port."""
66
+ try:
67
+ cmd: Optional[str] = {
68
+ "Windows": f"netstat -ano | findstr :{port}",
69
+ "Linux": f"ss -lntp | grep :{port}",
70
+ "Darwin": f"lsof -i :{port}",
71
+ }.get(platform.system())
72
+ if not cmd:
73
+ lgr.error(self._log_unsupported_os())
74
+ return None
75
+
76
+ process = subprocess.Popen(cmd, shell=True,
77
+ stdout=subprocess.PIPE,
78
+ stderr=subprocess.PIPE)
79
+ output, error = process.communicate()
80
+ if error:
81
+ lgr.error(self._log_cmd_error(error))
82
+ return None
83
+
84
+ lines: list[str] = output.decode().splitlines()
85
+ for line in lines:
86
+ if str(port) in line:
87
+ parts: list[str] = line.split()
88
+ if platform.system() == "Windows" and len(parts) > 4:
89
+ try:
90
+ return int(parts[4])
91
+ except ValueError:
92
+ lgr.error(self._log_line_parse_failed(line))
93
+ return None
94
+ elif platform.system() == "Linux":
95
+ for part in parts:
96
+ if "pid=" in part:
97
+ try:
98
+ return int(part.split("=")[1])
99
+ except ValueError:
100
+ lgr.error(self._log_line_parse_failed(line))
101
+ return None
102
+ elif platform.system() == "Darwin" and len(parts) > 1:
103
+ try:
104
+ return int(parts[1])
105
+ except ValueError:
106
+ lgr.error(self._log_line_parse_failed(line))
107
+ return None
108
+ return None
109
+ except Exception as e:
110
+ lgr.error(self._log_unexpected_error(e))
111
+ return None
112
+
113
+ def kill_process(self, pid: int) -> bool:
114
+ """Kills the process with the specified PID."""
115
+ try:
116
+ cmd: Optional[str] = {
117
+ 'Windows': f'taskkill /F /PID {pid}',
118
+ 'Linux': f'kill -9 {pid}',
119
+ 'Darwin': f'kill -9 {pid}',
120
+ }.get(platform.system())
121
+ if not cmd:
122
+ lgr.error(self._log_unsupported_os())
123
+ return False
124
+ process = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
125
+ _, error = process.communicate()
126
+ if process.returncode:
127
+ error_msg = error.decode()
128
+ lgr.error(self._log_terminate_failed(pid=pid, error=error_msg))
129
+ return False
130
+ return True
131
+ except Exception as e:
132
+ lgr.error(self._log_unexpected_error(e))
133
+ return False
134
+
135
+ def release_all(self, ports: Optional[list[int]] = None) -> None:
136
+ try:
137
+ ports_to_release: list[int] = self.default_ports if ports is None else ports
138
+
139
+ for port in ports_to_release:
140
+ if not isinstance(port, int):
141
+ lgr.error(self._log_invalid_port(port))
142
+ continue
143
+
144
+ pid: Optional[int] = self.get_pid_by_port(port)
145
+ if pid is None:
146
+ lgr.info(self._log_no_process(port))
147
+ continue
148
+
149
+ lgr.info(self._log_process_found(port, pid))
150
+ if self.kill_process(pid):
151
+ lgr.info(self._log_process_terminated(pid, port))
152
+ else:
153
+ lgr.error(self._log_terminate_failed(pid=pid, port=port))
154
+ except Exception as e:
155
+ lgr.error(self._log_unexpected_error(e))
156
+
@@ -0,0 +1,24 @@
1
+ from functools import wraps
2
+ import time
3
+
4
+
5
+ class Timer:
6
+ def __init__(self, precision=4, verbose=False):
7
+ self.precision = precision
8
+ self.verbose = verbose
9
+
10
+ def timeit(self, func):
11
+ @wraps(func)
12
+ def timeit_wrapper(*args, **kwargs):
13
+ start_time = time.perf_counter()
14
+ result = func(*args, **kwargs)
15
+ end_time = time.perf_counter()
16
+ total_time = end_time - start_time
17
+ extra_info = f'{args} {kwargs} ' if self.verbose else ''
18
+ print(f'{func.__name__} {extra_info}took {total_time:.{self.precision}f} [s]')
19
+ return result
20
+ return timeit_wrapper
21
+
22
+
23
+
24
+
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.4
2
+ Name: nano_dev_utils
3
+ Version: 0.2.1
4
+ Summary: A collection of small Python utilities for developers.
5
+ Project-URL: Homepage, https://github.com/yaronday/nano_utils
6
+ Project-URL: Issues, https://github.com/yaronday/nano_utils/issues
7
+ Author-email: Yaron Dayan <yaronday77@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE.md
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+
15
+ # nano_dev_utils
16
+
17
+ A collection of small Python utilities for developers.
18
+
19
+ ## Modules
20
+
21
+ ### `timers.py`
22
+
23
+ This module provides a `Timer` class for measuring the execution time of code blocks and functions.
24
+
25
+ #### `Timer` Class
26
+
27
+ * **`__init__(self, precision=4, verbose=False)`**: Initializes a `Timer` instance.
28
+ * `precision` (int, optional): The number of decimal places to record and
29
+ * display time durations. Defaults to 4.
30
+ * `verbose` (bool, optional): If `True`, the function's arguments and keyword
31
+ * arguments will be included in the printed timing output. Defaults to `False`.
32
+ * `timing_records` (list): A list to store the recorded timing durations as formatted strings.
33
+
34
+ * **`timeit(self, func)`**: A decorator that measures the execution time of the decorated function.
35
+ * When the decorated function is called, this decorator records the start and end times,
36
+ * calculates the total execution time, prints the function name and execution time
37
+ * (optionally including arguments if `verbose` is `True`), and returns the result of the original function.
38
+
39
+ #### Example Usage:
40
+
41
+ ```python
42
+ import time
43
+ from src.nano_dev_utils.timers import Timer
44
+
45
+ timer = Timer(precision=6, verbose=True)
46
+
47
+
48
+ @timer.timeit
49
+ def my_function(a, b=10):
50
+ """A sample function."""
51
+ time.sleep(0.1)
52
+ return a + b
53
+
54
+
55
+ result = my_function(5, b=20)
56
+ print(f"Result: {result}")
57
+ ```
58
+
59
+ ### `dynamic_importer.py`
60
+
61
+ This module provides an `Importer` class for lazy loading and caching module imports.
62
+
63
+ #### `Importer` Class
64
+
65
+ * **`__init__(self)`**: Initializes an `Importer` instance with an empty dictionary `imported_modules` to cache imported modules.
66
+
67
+ * **`import_mod_from_lib(self, library: str, module_name: str) -> ModuleType | Any`**: Lazily imports a module from a specified library and caches it.
68
+ * `library` (str): The name of the library (e.g., "os", "requests").
69
+ * `module_name` (str): The name of the module to import within the library (e.g., "path", "get").
70
+ * Returns the imported module. If the module has already been imported, it returns the cached instance.
71
+ * Raises `ImportError` if the module cannot be found.
72
+
73
+ #### Example Usage:
74
+
75
+ ```python
76
+ from src.nano_dev_utils.dynamic_importer import Importer
77
+
78
+ importer = Importer()
79
+
80
+ os_path = importer.import_mod_from_lib("os", "path")
81
+ print(f"Imported os.path: {os_path}")
82
+
83
+ requests_get = importer.import_mod_from_lib("requests", "get")
84
+ print(f"Imported requests.get: {requests_get}")
85
+
86
+ # Subsequent calls will return the cached module
87
+ os_path_again = importer.import_mod_from_lib("os", "path")
88
+ print(f"Imported os.path again (cached): {os_path_again}")
89
+ ```
90
+
91
+ ### `release_ports.py`
92
+
93
+ This module provides a `PortsRelease` class to identify and release processes
94
+ listening on specified TCP ports. It supports Windows, Linux, and macOS.
95
+
96
+ #### `PortsRelease` Class
97
+
98
+ * **`__init__(self, default_ports: Optional[list[int]] = None)`**:
99
+ * Initializes a `PortsRelease` instance.
100
+ * `default_ports` (`list[int]`, *optional*): A list of default ports to manage.
101
+ * If not provided, it defaults to `[6277, 6274]`.
102
+
103
+ * **`get_pid_by_port(port: int) -> Optional[int]`**: A static method that attempts to
104
+ * find the process ID (PID) listening on the given `port`. It uses platform-specific
105
+ * commands (`netstat`, `ss`, `lsof`). Returns the PID if found, otherwise `None`.
106
+
107
+ * **`kill_process(pid: int) -> bool`**: A static method that attempts to kill the process
108
+ * with the given `pid`. It uses platform-specific commands (`taskkill`, `kill -9`).
109
+ * Returns `True` if the process was successfully killed, `False` otherwise.
110
+
111
+ * **`release_all(self, ports: Optional[list[int]] = None) -> None`**: Releases all processes
112
+ * listening on the specified `ports`.
113
+ * `ports` (`list[int]`, *optional*): A list of ports to release. If `None`, it uses the
114
+ * `default_ports` defined during initialization.
115
+ * For each port, it first tries to get the PID and then attempts to kill the process.
116
+ * It logs the actions and any errors encountered. Invalid port numbers in the provided list are skipped.
117
+
118
+ #### Example Usage:
119
+
120
+ ```python
121
+ from src.nano_dev_utils.release_ports import PortsRelease
122
+
123
+ # Create an instance with default ports
124
+ port_releaser = PortsRelease()
125
+ port_releaser.release_all()
126
+
127
+ # Create an instance with custom ports
128
+ custom_ports_releaser = PortsRelease(default_ports=[8080, 9000, 6274])
129
+ custom_ports_releaser.release_all(ports=[8080, 9000])
130
+
131
+ # Release only the default ports
132
+ port_releaser.release_all()
133
+ ```
134
+
135
+ ## License
136
+ This project is licensed under the MIT License.
137
+ See [LICENSE](https://github.com/yaronday/nano_dev_utils/blob/master/README.md) for details.
@@ -0,0 +1,8 @@
1
+ nano_dev_utils/__init__.py,sha256=qcbhac5zx27mAgmNvwwHzNxyYsMRK-WElB8n4e8c81A,374
2
+ nano_dev_utils/dynamic_importer.py,sha256=sW09aj3_6tzm6mOQbBuqZjp6O2PnpG0_2Ol4Zs_nXe4,902
3
+ nano_dev_utils/release_ports.py,sha256=HpKL7kawNrLE5RPLByoX_nflaLkQfTnlZKyEIZqSG8g,6081
4
+ nano_dev_utils/timers.py,sha256=_WBY0EQLTn3m-41hw0bzpZ2jR9jn2pmbhfAOWmQkKho,690
5
+ nano_dev_utils-0.2.1.dist-info/METADATA,sha256=561_a1OX9cNMOcu_0cabbp86RfgjjWUHpSAMNGkdqtU,5159
6
+ nano_dev_utils-0.2.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ nano_dev_utils-0.2.1.dist-info/licenses/LICENSE.md,sha256=Muenl7Bw_LdtHZtlOMAP7Kt97gDCq8WWp2605eDWhHU,1089
8
+ nano_dev_utils-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Yaron Dayan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.