nano-dev-utils 0.5.6__tar.gz → 0.5.8__tar.gz

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,3 @@
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
@@ -0,0 +1,6 @@
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
@@ -0,0 +1,7 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Black">
4
+ <option name="sdkName" value="Python 3.10" />
5
+ </component>
6
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (nano_dev_utils)" project-jdk-type="Python SDK" />
7
+ </project>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/nano_dev_utils.iml" filepath="$PROJECT_DIR$/.idea/nano_dev_utils.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
@@ -0,0 +1,10 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
6
+ </content>
7
+ <orderEntry type="jdk" jdkName="Python 3.10 (nano_dev_utils)" jdkType="Python SDK" />
8
+ <orderEntry type="sourceFolder" forTests="false" />
9
+ </component>
10
+ </module>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,247 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="1859e23b-7665-4b92-98cc-65e07a208923" name="Changes" comment="corrected return types - complete">
8
+ <change beforePath="$PROJECT_DIR$/README.md" beforeDir="false" afterPath="$PROJECT_DIR$/README.md" afterDir="false" />
9
+ <change beforePath="$PROJECT_DIR$/pyproject.toml" beforeDir="false" afterPath="$PROJECT_DIR$/pyproject.toml" afterDir="false" />
10
+ <change beforePath="$PROJECT_DIR$/src/nano_dev_utils/timers.py" beforeDir="false" afterPath="$PROJECT_DIR$/src/nano_dev_utils/timers.py" afterDir="false" />
11
+ <change beforePath="$PROJECT_DIR$/tests/test_timer.py" beforeDir="false" afterPath="$PROJECT_DIR$/tests/test_timer.py" afterDir="false" />
12
+ </list>
13
+ <option name="SHOW_DIALOG" value="false" />
14
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
15
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
16
+ <option name="LAST_RESOLUTION" value="IGNORE" />
17
+ </component>
18
+ <component name="Git.Settings">
19
+ <option name="RECENT_BRANCH_BY_REPOSITORY">
20
+ <map>
21
+ <entry key="$PROJECT_DIR$" value="FI" />
22
+ </map>
23
+ </option>
24
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
25
+ </component>
26
+ <component name="ProjectColorInfo">{
27
+ &quot;customColor&quot;: &quot;&quot;,
28
+ &quot;associatedIndex&quot;: 5
29
+ }</component>
30
+ <component name="ProjectId" id="2wVV0HQbcggEgX5PEayC1Mcx9Gd" />
31
+ <component name="ProjectViewState">
32
+ <option name="hideEmptyMiddlePackages" value="true" />
33
+ <option name="showLibraryContents" value="true" />
34
+ <option name="showMembers" value="true" />
35
+ </component>
36
+ <component name="PropertiesComponent"><![CDATA[{
37
+ "keyToString": {
38
+ "Python tests.Python tests in test_timer.py.executor": "Run",
39
+ "Python tests.Python tests in tests.executor": "Run",
40
+ "Python.test_timer.executor": "Run",
41
+ "RunOnceActivity.ShowReadmeOnStart": "true",
42
+ "git-widget-placeholder": "master",
43
+ "ignore.virus.scanning.warn.message": "true",
44
+ "last_opened_file_path": "C:/GitHubWS/nano_dev_utils",
45
+ "settings.editor.selected.configurable": "com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable"
46
+ }
47
+ }]]></component>
48
+ <component name="RecentsManager">
49
+ <key name="CopyFile.RECENT_KEYS">
50
+ <recent name="C:\GitHubWS\nano_dev_utils" />
51
+ </key>
52
+ </component>
53
+ <component name="RunManager" selected="Python tests.Python tests in tests">
54
+ <configuration name="test_timer" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
55
+ <module name="nano_dev_utils" />
56
+ <option name="ENV_FILES" value="" />
57
+ <option name="INTERPRETER_OPTIONS" value="" />
58
+ <option name="PARENT_ENVS" value="true" />
59
+ <envs>
60
+ <env name="PYTHONUNBUFFERED" value="1" />
61
+ </envs>
62
+ <option name="SDK_HOME" value="" />
63
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/tests" />
64
+ <option name="IS_MODULE_SDK" value="true" />
65
+ <option name="ADD_CONTENT_ROOTS" value="true" />
66
+ <option name="ADD_SOURCE_ROOTS" value="true" />
67
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/tests/test_timer.py" />
68
+ <option name="PARAMETERS" value="" />
69
+ <option name="SHOW_COMMAND_LINE" value="false" />
70
+ <option name="EMULATE_TERMINAL" value="false" />
71
+ <option name="MODULE_MODE" value="false" />
72
+ <option name="REDIRECT_INPUT" value="false" />
73
+ <option name="INPUT_FILE" value="" />
74
+ <method v="2" />
75
+ </configuration>
76
+ <configuration name="Python tests in test_timer.py" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
77
+ <module name="nano_dev_utils" />
78
+ <option name="ENV_FILES" value="" />
79
+ <option name="INTERPRETER_OPTIONS" value="" />
80
+ <option name="PARENT_ENVS" value="true" />
81
+ <option name="SDK_HOME" value="" />
82
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/tests" />
83
+ <option name="IS_MODULE_SDK" value="true" />
84
+ <option name="ADD_CONTENT_ROOTS" value="true" />
85
+ <option name="ADD_SOURCE_ROOTS" value="true" />
86
+ <option name="_new_additionalArguments" value="&quot;&quot;" />
87
+ <option name="_new_target" value="&quot;$PROJECT_DIR$/tests/test_timer.py&quot;" />
88
+ <option name="_new_targetType" value="&quot;PATH&quot;" />
89
+ <method v="2" />
90
+ </configuration>
91
+ <configuration name="Python tests in tests" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
92
+ <module name="nano_dev_utils" />
93
+ <option name="ENV_FILES" value="" />
94
+ <option name="INTERPRETER_OPTIONS" value="" />
95
+ <option name="PARENT_ENVS" value="true" />
96
+ <option name="SDK_HOME" value="" />
97
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/tests" />
98
+ <option name="IS_MODULE_SDK" value="true" />
99
+ <option name="ADD_CONTENT_ROOTS" value="true" />
100
+ <option name="ADD_SOURCE_ROOTS" value="true" />
101
+ <option name="_new_additionalArguments" value="&quot;&quot;" />
102
+ <option name="_new_target" value="&quot;$PROJECT_DIR$/tests&quot;" />
103
+ <option name="_new_targetType" value="&quot;PATH&quot;" />
104
+ <method v="2" />
105
+ </configuration>
106
+ <recent_temporary>
107
+ <list>
108
+ <item itemvalue="Python tests.Python tests in tests" />
109
+ <item itemvalue="Python tests.Python tests in tests" />
110
+ <item itemvalue="Python tests.Python tests in test_timer.py" />
111
+ <item itemvalue="Python.test_timer" />
112
+ </list>
113
+ </recent_temporary>
114
+ </component>
115
+ <component name="SharedIndexes">
116
+ <attachedChunks>
117
+ <set>
118
+ <option value="bundled-python-sdk-5b207ade9991-746f403e7f0c-com.jetbrains.pycharm.community.sharedIndexes.bundled-PC-241.17890.14" />
119
+ </set>
120
+ </attachedChunks>
121
+ </component>
122
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
123
+ <component name="TaskManager">
124
+ <task active="true" id="Default" summary="Default task">
125
+ <changelist id="1859e23b-7665-4b92-98cc-65e07a208923" name="Changes" comment="" />
126
+ <created>1746126505743</created>
127
+ <option name="number" value="Default" />
128
+ <option name="presentableId" value="Default" />
129
+ <updated>1746126505743</updated>
130
+ </task>
131
+ <task id="LOCAL-00001" summary=".">
132
+ <option name="closed" value="true" />
133
+ <created>1746126585369</created>
134
+ <option name="number" value="00001" />
135
+ <option name="presentableId" value="LOCAL-00001" />
136
+ <option name="project" value="LOCAL" />
137
+ <updated>1746126585369</updated>
138
+ </task>
139
+ <task id="LOCAL-00002" summary="license relative path">
140
+ <option name="closed" value="true" />
141
+ <created>1746126934201</created>
142
+ <option name="number" value="00002" />
143
+ <option name="presentableId" value="LOCAL-00002" />
144
+ <option name="project" value="LOCAL" />
145
+ <updated>1746126934201</updated>
146
+ </task>
147
+ <task id="LOCAL-00003" summary="license file renamed">
148
+ <option name="closed" value="true" />
149
+ <created>1746127675699</created>
150
+ <option name="number" value="00003" />
151
+ <option name="presentableId" value="LOCAL-00003" />
152
+ <option name="project" value="LOCAL" />
153
+ <updated>1746127675699</updated>
154
+ </task>
155
+ <task id="LOCAL-00004" summary="adding license path">
156
+ <option name="closed" value="true" />
157
+ <created>1746127874421</created>
158
+ <option name="number" value="00004" />
159
+ <option name="presentableId" value="LOCAL-00004" />
160
+ <option name="project" value="LOCAL" />
161
+ <updated>1746127874421</updated>
162
+ </task>
163
+ <task id="LOCAL-00005" summary="adding license url">
164
+ <option name="closed" value="true" />
165
+ <created>1746128395309</created>
166
+ <option name="number" value="00005" />
167
+ <option name="presentableId" value="LOCAL-00005" />
168
+ <option name="project" value="LOCAL" />
169
+ <updated>1746128395310</updated>
170
+ </task>
171
+ <task id="LOCAL-00006" summary="+pre-commit config">
172
+ <option name="closed" value="true" />
173
+ <created>1746694280668</created>
174
+ <option name="number" value="00006" />
175
+ <option name="presentableId" value="LOCAL-00006" />
176
+ <option name="project" value="LOCAL" />
177
+ <updated>1746694280668</updated>
178
+ </task>
179
+ <task id="LOCAL-00007" summary="removed [tool.hatch.build]">
180
+ <option name="closed" value="true" />
181
+ <created>1747321637844</created>
182
+ <option name="number" value="00007" />
183
+ <option name="presentableId" value="LOCAL-00007" />
184
+ <option name="project" value="LOCAL" />
185
+ <updated>1747321637844</updated>
186
+ </task>
187
+ <task id="LOCAL-00008" summary="+iterations parameter">
188
+ <option name="closed" value="true" />
189
+ <created>1747660086270</created>
190
+ <option name="number" value="00008" />
191
+ <option name="presentableId" value="LOCAL-00008" />
192
+ <option name="project" value="LOCAL" />
193
+ <updated>1747660086270</updated>
194
+ </task>
195
+ <task id="LOCAL-00009" summary="minor update">
196
+ <option name="closed" value="true" />
197
+ <created>1747661192289</created>
198
+ <option name="number" value="00009" />
199
+ <option name="presentableId" value="LOCAL-00009" />
200
+ <option name="project" value="LOCAL" />
201
+ <updated>1747661192289</updated>
202
+ </task>
203
+ <task id="LOCAL-00010" summary="corrected return type">
204
+ <option name="closed" value="true" />
205
+ <created>1747665494128</created>
206
+ <option name="number" value="00010" />
207
+ <option name="presentableId" value="LOCAL-00010" />
208
+ <option name="project" value="LOCAL" />
209
+ <updated>1747665494128</updated>
210
+ </task>
211
+ <task id="LOCAL-00011" summary="corrected return types - complete">
212
+ <option name="closed" value="true" />
213
+ <created>1747666293914</created>
214
+ <option name="number" value="00011" />
215
+ <option name="presentableId" value="LOCAL-00011" />
216
+ <option name="project" value="LOCAL" />
217
+ <updated>1747666293914</updated>
218
+ </task>
219
+ <option name="localTasksCounter" value="12" />
220
+ <servers />
221
+ </component>
222
+ <component name="Vcs.Log.Tabs.Properties">
223
+ <option name="TAB_STATES">
224
+ <map>
225
+ <entry key="MAIN">
226
+ <value>
227
+ <State />
228
+ </value>
229
+ </entry>
230
+ </map>
231
+ </option>
232
+ </component>
233
+ <component name="VcsManagerConfiguration">
234
+ <MESSAGE value="." />
235
+ <MESSAGE value="license relative path" />
236
+ <MESSAGE value="license file renamed" />
237
+ <MESSAGE value="adding license path" />
238
+ <MESSAGE value="adding license url" />
239
+ <MESSAGE value="+pre-commit config" />
240
+ <MESSAGE value="removed [tool.hatch.build]" />
241
+ <MESSAGE value="+iterations parameter" />
242
+ <MESSAGE value="minor update" />
243
+ <MESSAGE value="corrected return type" />
244
+ <MESSAGE value="corrected return types - complete" />
245
+ <option name="LAST_COMMIT_MESSAGE" value="corrected return types - complete" />
246
+ </component>
247
+ </project>
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nano_dev_utils
3
- Version: 0.5.6
3
+ Version: 0.5.8
4
4
  Summary: A collection of small Python utilities for developers.
5
5
  Project-URL: Homepage, https://github.com/yaronday/nano_utils
6
6
  Project-URL: Issues, https://github.com/yaronday/nano_utils/issues
@@ -34,10 +34,12 @@ This module provides a `Timer` class for measuring the execution time of code bl
34
34
  * `verbose`: Optionally displays the function's positional arguments (args) and keyword arguments (kwargs).
35
35
  Defaults to `False`.
36
36
 
37
- * **`timeit(self, func: Callable[P, R]) -> Callable[P, R]`**:
37
+ * **`timeit(
38
+ self, iterations: int = 1
39
+ ) -> Callable[[Callable[P, R]], Callable[P, R | None]]`**:
38
40
  Decorator that times function execution with automatic unit scaling.
39
41
  * When the decorated function is called, this decorator records the start and end times,
40
- calculates the total execution time, prints the function name and execution
42
+ calculates the average execution time, prints the function name and execution
41
43
  time (optionally including arguments), and returns the result of the original function.
42
44
 
43
45
  #### Example Usage:
@@ -49,7 +51,7 @@ from nano_dev_utils.timers import Timer
49
51
  timer = Timer(precision=6, verbose=True)
50
52
 
51
53
 
52
- @timer.timeit
54
+ @timer.timeit()
53
55
  def my_function(a, b=10):
54
56
  """A sample function."""
55
57
  time.sleep(0.1)
@@ -16,10 +16,12 @@ This module provides a `Timer` class for measuring the execution time of code bl
16
16
  * `verbose`: Optionally displays the function's positional arguments (args) and keyword arguments (kwargs).
17
17
  Defaults to `False`.
18
18
 
19
- * **`timeit(self, func: Callable[P, R]) -> Callable[P, R]`**:
19
+ * **`timeit(
20
+ self, iterations: int = 1
21
+ ) -> Callable[[Callable[P, R]], Callable[P, R | None]]`**:
20
22
  Decorator that times function execution with automatic unit scaling.
21
23
  * When the decorated function is called, this decorator records the start and end times,
22
- calculates the total execution time, prints the function name and execution
24
+ calculates the average execution time, prints the function name and execution
23
25
  time (optionally including arguments), and returns the result of the original function.
24
26
 
25
27
  #### Example Usage:
@@ -31,7 +33,7 @@ from nano_dev_utils.timers import Timer
31
33
  timer = Timer(precision=6, verbose=True)
32
34
 
33
35
 
34
- @timer.timeit
36
+ @timer.timeit()
35
37
  def my_function(a, b=10):
36
38
  """A sample function."""
37
39
  time.sleep(0.1)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "nano_dev_utils"
3
- version = "0.5.6"
3
+ version = "0.5.8"
4
4
 
5
5
  authors = [
6
6
  { name="Yaron Dayan", email="yaronday77@gmail.com" },
@@ -32,5 +32,3 @@ license = "https://github.com/yaronday/nano_dev_utils/blob/master/LICENSE"
32
32
  requires = ["hatchling >= 1.26"]
33
33
  build-backend = "hatchling.build"
34
34
 
35
- [tool.hatch.build]
36
- include = ["LICENSE"]
@@ -0,0 +1,18 @@
1
+ """nano-dev-utils - A collection of small Python utilities for developers.
2
+ Copyright (c) 2025 Yaron Dayan
3
+ """
4
+
5
+ from .dynamic_importer import Importer
6
+ from .timers import Timer
7
+ from .release_ports import PortsRelease, PROXY_SERVER, INSPECTOR_CLIENT
8
+ from importlib.metadata import version
9
+
10
+ __version__ = version('nano-dev-utils')
11
+
12
+ __all__ = [
13
+ 'Importer',
14
+ 'Timer',
15
+ 'PortsRelease',
16
+ 'PROXY_SERVER',
17
+ 'INSPECTOR_CLIENT',
18
+ ]
@@ -0,0 +1,27 @@
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
+ lib_mod = f'{library}.{module_name}'
21
+
22
+ try:
23
+ module = importlib.import_module(lib_mod)
24
+ self.imported_modules[module_name] = module
25
+ return module
26
+ except ModuleNotFoundError as e:
27
+ raise ImportError(f'Could not import {lib_mod}') from e
@@ -0,0 +1,155 @@
1
+ import platform
2
+ import subprocess
3
+ import logging
4
+
5
+ lgr = logging.getLogger(__name__)
6
+ """Module-level logger. Configure using logging.basicConfig() in your application."""
7
+
8
+ PROXY_SERVER = 6277
9
+ INSPECTOR_CLIENT = 6274
10
+
11
+
12
+ class PortsRelease:
13
+ def __init__(self, default_ports: list[int] | None = None):
14
+ self.default_ports: list[int] = (
15
+ default_ports
16
+ if default_ports is not None
17
+ else [PROXY_SERVER, INSPECTOR_CLIENT]
18
+ )
19
+
20
+ @staticmethod
21
+ def _log_process_found(port: int, pid: int) -> str:
22
+ return f'Process ID (PID) found for port {port}: {pid}.'
23
+
24
+ @staticmethod
25
+ def _log_process_terminated(pid: int, port: int) -> str:
26
+ return f'Process {pid} (on port {port}) terminated successfully.'
27
+
28
+ @staticmethod
29
+ def _log_no_process(port: int) -> str:
30
+ return f'No process found listening on port {port}.'
31
+
32
+ @staticmethod
33
+ def _log_invalid_port(port: int) -> str:
34
+ return f'Invalid port number: {port}. Skipping.'
35
+
36
+ @staticmethod
37
+ def _log_terminate_failed(
38
+ pid: int, port: int | None = None, error: str | None = None
39
+ ) -> str:
40
+ base_msg = f'Failed to terminate process {pid}'
41
+ if port:
42
+ base_msg += f' (on port {port})'
43
+ if error:
44
+ base_msg += f'. Error: {error}'
45
+ return base_msg
46
+
47
+ @staticmethod
48
+ def _log_line_parse_failed(line: str) -> str:
49
+ return f'Could not parse PID from line: {line}'
50
+
51
+ @staticmethod
52
+ def _log_unexpected_error(e: Exception) -> str:
53
+ return f'An unexpected error occurred: {e}'
54
+
55
+ @staticmethod
56
+ def _log_cmd_error(error: bytes) -> str:
57
+ return f'Error running command: {error.decode()}'
58
+
59
+ @staticmethod
60
+ def _log_unsupported_os() -> str:
61
+ return f'Unsupported OS: {platform.system()}'
62
+
63
+ def get_pid_by_port(self, port: int) -> int | None:
64
+ """Gets the process ID (PID) listening on the specified port."""
65
+ system = platform.system()
66
+ try:
67
+ cmd: str = {
68
+ 'Windows': f'netstat -ano | findstr :{port}',
69
+ 'Linux': f'ss -lntp | grep :{port}',
70
+ 'Darwin': f'lsof -i :{port}',
71
+ }.get(system, '')
72
+ if not cmd:
73
+ lgr.error(self._log_unsupported_os())
74
+ return None
75
+
76
+ process = subprocess.Popen(
77
+ cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
78
+ )
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 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 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 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: str = {
117
+ 'Windows': f'taskkill /F /PID {pid}',
118
+ 'Linux': f'kill -9 {pid}',
119
+ 'Darwin': f'kill -9 {pid}',
120
+ }.get(platform.system(), '') # fallback to empty string
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: list[int] | None = 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: int | None = 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))
@@ -0,0 +1,49 @@
1
+ from functools import wraps
2
+ import time
3
+ from typing import Callable, ParamSpec, TypeVar
4
+
5
+ P = ParamSpec('P')
6
+ R = TypeVar('R')
7
+
8
+
9
+ class Timer:
10
+ def __init__(self, precision=4, verbose=False):
11
+ self.precision = precision
12
+ self.verbose = verbose
13
+ self.units = [(1e9, 's'), (1e6, 'ms'), (1e3, 'μs'), (1.0, 'ns')]
14
+
15
+ def timeit(
16
+ self, iterations: int = 1
17
+ ) -> Callable[[Callable[P, R]], Callable[P, R | None]]:
18
+ def decorator(func: Callable[P, R]) -> Callable[P, R | None]:
19
+ """Decorator that times function execution with automatic unit scaling and averaging."""
20
+
21
+ @wraps(func)
22
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
23
+ total_elapsed = 0
24
+ result = None
25
+
26
+ for _ in range(iterations):
27
+ start = time.perf_counter_ns()
28
+ result = func(*args, **kwargs)
29
+ total_elapsed += time.perf_counter_ns() - start
30
+
31
+ avg_elapsed = total_elapsed / iterations
32
+ value = avg_elapsed
33
+ unit = 'ns'
34
+
35
+ for divisor, unit in self.units:
36
+ if avg_elapsed >= divisor or unit == 'ns':
37
+ value = avg_elapsed / divisor
38
+ break
39
+
40
+ extra_info = f'{args} {kwargs} ' if self.verbose else ''
41
+ iter_info = f' (avg over {iterations} runs)' if iterations > 1 else ''
42
+ print(
43
+ f'{func.__name__} {extra_info}took {value:.{self.precision}f} [{unit}]{iter_info}'
44
+ )
45
+ return result
46
+
47
+ return wrapper
48
+
49
+ return decorator
@@ -0,0 +1,10 @@
1
+ """nano-dev-utils - A collection of small Python utilities for developers.
2
+ Copyright (c) 2025 Yaron Dayan
3
+ """
4
+
5
+ from .test_release_ports import PROXY_SERVER, CLIENT_PORT
6
+
7
+ __all__ = [
8
+ 'PROXY_SERVER',
9
+ 'CLIENT_PORT',
10
+ ]