virtualshell 1.0.0__cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.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.
- virtualshell/__init__.py +36 -0
- virtualshell/_core.cpython-312-aarch64-linux-gnu.so +0 -0
- virtualshell/_version.py +1 -0
- virtualshell/errors.py +4 -0
- virtualshell/shell.py +515 -0
- virtualshell-1.0.0.dist-info/METADATA +461 -0
- virtualshell-1.0.0.dist-info/RECORD +9 -0
- virtualshell-1.0.0.dist-info/WHEEL +6 -0
- virtualshell-1.0.0.dist-info/licenses/LICENSE +201 -0
virtualshell/__init__.py
ADDED
@@ -0,0 +1,36 @@
|
|
1
|
+
from __future__ import annotations
|
2
|
+
from importlib import import_module
|
3
|
+
from typing import TYPE_CHECKING
|
4
|
+
|
5
|
+
if TYPE_CHECKING:
|
6
|
+
from .shell import ExecutionResult, Shell
|
7
|
+
|
8
|
+
try:
|
9
|
+
from ._version import version as __version__
|
10
|
+
except Exception:
|
11
|
+
__version__ = "0.1.2"
|
12
|
+
|
13
|
+
|
14
|
+
from .errors import (
|
15
|
+
VirtualShellError,
|
16
|
+
PowerShellNotFoundError,
|
17
|
+
ExecutionTimeoutError,
|
18
|
+
ExecutionError,
|
19
|
+
)
|
20
|
+
|
21
|
+
__all__ = [
|
22
|
+
"VirtualShellError", "PowerShellNotFoundError",
|
23
|
+
"ExecutionTimeoutError", "ExecutionError",
|
24
|
+
"__version__", "Shell", "ExecutionResult",
|
25
|
+
]
|
26
|
+
|
27
|
+
def __getattr__(name: str):
|
28
|
+
if name in {"Shell", "ExecutionResult"}:
|
29
|
+
mod = import_module(".shell", __name__)
|
30
|
+
obj = getattr(mod, name)
|
31
|
+
globals()[name] = obj
|
32
|
+
return obj
|
33
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
34
|
+
|
35
|
+
def __dir__():
|
36
|
+
return sorted(__all__)
|
Binary file
|
virtualshell/_version.py
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
version = "0.1.2"
|
virtualshell/errors.py
ADDED
virtualshell/shell.py
ADDED
@@ -0,0 +1,515 @@
|
|
1
|
+
"""
|
2
|
+
High-level: Python façade over a C++ PowerShell runner (virtualshell_core).
|
3
|
+
|
4
|
+
Design goals (production-readiness):
|
5
|
+
- **Thin wrapper**: All heavy I/O and process orchestration live in C++ for performance.
|
6
|
+
- **No surprises**: Stable API; no implicit state mutations beyond what is documented.
|
7
|
+
- **Clear failure modes**: Dedicated exceptions and `raise_on_error` semantics.
|
8
|
+
- **Thread-friendly**: Async methods return Futures and accept callbacks; no Python-side locks.
|
9
|
+
- **Boundary hygiene**: Minimal data marshalling; explicit conversions for paths/args.
|
10
|
+
|
11
|
+
Security notes:
|
12
|
+
- This wrapper does not sanitize commands. Only `pwsh()` uses literal quoting via `quote_pwsh_literal()`.
|
13
|
+
- Do *not* pass untrusted strings to `execute*` unless you quote/sanitize appropriately.
|
14
|
+
- Environment injection occurs via Config; avoid leaking secrets in logs/tracebacks.
|
15
|
+
|
16
|
+
Perf notes:
|
17
|
+
- All sync/async execution routes call into C++ directly. Python overhead is dominated by
|
18
|
+
object creation and callback dispatch. Keep callbacks lean.
|
19
|
+
- Prefer batch/async when issuing many small commands to amortize round-trips.
|
20
|
+
|
21
|
+
Lifetime:
|
22
|
+
- `Shell.start()` ensures there is a running backend process. `Shell.stop()` tears it down.
|
23
|
+
- Context manager (`with Shell(...) as sh:`) guarantees stop-on-exit.
|
24
|
+
|
25
|
+
Compatibility:
|
26
|
+
- The C++ layer may expose both snake_case and camelCase fields; `ExecutionResult.from_cpp()`
|
27
|
+
maps both to keep ABI compatibility.
|
28
|
+
"""
|
29
|
+
from __future__ import annotations
|
30
|
+
|
31
|
+
import importlib
|
32
|
+
from dataclasses import dataclass
|
33
|
+
from pathlib import Path
|
34
|
+
from typing import Iterable, List, Dict, Optional, Callable, Any, Union
|
35
|
+
import concurrent.futures as cf
|
36
|
+
|
37
|
+
|
38
|
+
_CPP_MODULE: Any = None
|
39
|
+
|
40
|
+
import importlib
|
41
|
+
try:
|
42
|
+
_CPP_MODULE = importlib.import_module(f"{__package__}._core")
|
43
|
+
except Exception as e:
|
44
|
+
raise ImportError(
|
45
|
+
"Failed to import the compiled extension 'virtualshell._core'. "
|
46
|
+
"Make sure it was built and matches this Python/platform."
|
47
|
+
) from e
|
48
|
+
|
49
|
+
|
50
|
+
# Aliases to reduce attribute lookups on the hot path.
|
51
|
+
_CPP_VirtualShell = _CPP_MODULE.VirtualShell
|
52
|
+
_CPP_Config = _CPP_MODULE.Config
|
53
|
+
_CPP_ExecResult = _CPP_MODULE.ExecutionResult
|
54
|
+
_CPP_BatchProg = _CPP_MODULE.BatchProgress
|
55
|
+
|
56
|
+
|
57
|
+
# ---------- Exceptions ----------
|
58
|
+
# Narrow, typed exceptions help callers implement precise retry/telemetry policies.
|
59
|
+
from .errors import (
|
60
|
+
VirtualShellError,
|
61
|
+
PowerShellNotFoundError,
|
62
|
+
ExecutionTimeoutError,
|
63
|
+
ExecutionError,
|
64
|
+
)
|
65
|
+
|
66
|
+
# ---------- Utils ----------
|
67
|
+
def quote_pwsh_literal(s: str) -> str:
|
68
|
+
"""Return a PowerShell *single-quoted* literal for arbitrary text `s`.
|
69
|
+
|
70
|
+
Rules:
|
71
|
+
- Empty string => `''` (empty single-quoted literal)
|
72
|
+
- Single quotes are doubled inside the literal per PowerShell rules.
|
73
|
+
- No interpolation/expansion occurs within single quotes in PowerShell.
|
74
|
+
|
75
|
+
This is safe for *data-as-argument* scenarios, not for embedding raw code.
|
76
|
+
Use it to construct commands like: `Write-Output {literal}`.
|
77
|
+
"""
|
78
|
+
if not s:
|
79
|
+
return "''"
|
80
|
+
out: List[str] = []
|
81
|
+
append = out.append
|
82
|
+
append("'")
|
83
|
+
for ch in s:
|
84
|
+
append("''" if ch == "'" else ch)
|
85
|
+
append("'")
|
86
|
+
return "".join(out)
|
87
|
+
|
88
|
+
def _effective_timeout(user_timeout: Optional[float], default_seconds: float) -> float:
|
89
|
+
"""Resolve an effective timeout (seconds).
|
90
|
+
|
91
|
+
Priority:
|
92
|
+
1) `user_timeout` if provided and > 0
|
93
|
+
2) C++ config default (`default_seconds`)
|
94
|
+
|
95
|
+
Always returns a float >= 0.0.
|
96
|
+
"""
|
97
|
+
return float(user_timeout) if (user_timeout and user_timeout > 0) else float(default_seconds or 0.0)
|
98
|
+
|
99
|
+
|
100
|
+
def _raise_on_failure(
|
101
|
+
res: _CPP_ExecResult,
|
102
|
+
*,
|
103
|
+
raise_on_error: bool,
|
104
|
+
label: str,
|
105
|
+
timeout_used: Optional[float],
|
106
|
+
) -> None:
|
107
|
+
"""Translate a C++ result into Python exceptions when requested.
|
108
|
+
|
109
|
+
- If `res.success` is True: no-op.
|
110
|
+
- Timeout heuristic: if `exit_code == -1` and the error string mentions "timeout",
|
111
|
+
raise `ExecutionTimeoutError` with the effective timeout used.
|
112
|
+
- Otherwise, if `raise_on_error` is True, raise `ExecutionError` with details.
|
113
|
+
|
114
|
+
This keeps the default behavior non-throwing for bulk workflows while allowing
|
115
|
+
strict error handling in critical paths.
|
116
|
+
"""
|
117
|
+
if res.success:
|
118
|
+
return
|
119
|
+
err = (res.error or "")
|
120
|
+
if res.exit_code == -1 and "timeout" in err.lower():
|
121
|
+
raise ExecutionTimeoutError(f"{label} timed out after {timeout_used}s")
|
122
|
+
if raise_on_error:
|
123
|
+
msg = err if err else f"{label} failed with exit_code={res.exit_code}"
|
124
|
+
raise ExecutionError(msg)
|
125
|
+
|
126
|
+
|
127
|
+
def _map_future(src_fut: cf.Future, mapper: Callable[[Any], Any]) -> cf.Future:
|
128
|
+
"""Create a new Future that maps the result of `src_fut` through `mapper`.
|
129
|
+
|
130
|
+
- Preserves exception semantics: exceptions from `src_fut` or the mapper
|
131
|
+
are propagated to the mapped future.
|
132
|
+
- Avoids blocking the event loop / thread: uses `add_done_callback`.
|
133
|
+
"""
|
134
|
+
nfut: cf.Future = cf.Future()
|
135
|
+
|
136
|
+
def _done(f: cf.Future) -> None:
|
137
|
+
try:
|
138
|
+
nfut.set_result(mapper(f.result()))
|
139
|
+
except Exception as e: # Propagate mapping errors
|
140
|
+
nfut.set_exception(e)
|
141
|
+
|
142
|
+
src_fut.add_done_callback(_done)
|
143
|
+
return nfut
|
144
|
+
|
145
|
+
|
146
|
+
# ---------- Python façade ----------
|
147
|
+
@dataclass(frozen=True)
|
148
|
+
class ExecutionResult:
|
149
|
+
"""Immutable Python-side execution result for ergonomic access.
|
150
|
+
|
151
|
+
Mirrors fields from the C++ `ExecutionResult` (snake_case/camelCase tolerant):
|
152
|
+
- output: Captured STDOUT
|
153
|
+
- error: Captured STDERR or synthesized error text
|
154
|
+
- exit_code: Process/command exit code (convention: -1 often signals timeout)
|
155
|
+
- success: Normalized success flag provided by the backend
|
156
|
+
- execution_time: Seconds (float) measured by the backend
|
157
|
+
|
158
|
+
Use this class when you need a stable Pythonic type. If you require the raw C++
|
159
|
+
object (e.g., for zero-copy interop), pass `as_dataclass=False` to public APIs.
|
160
|
+
"""
|
161
|
+
out: str
|
162
|
+
err: str
|
163
|
+
exit_code: int
|
164
|
+
success: bool
|
165
|
+
execution_time: float
|
166
|
+
|
167
|
+
@classmethod
|
168
|
+
def from_cpp(cls, r: _CPP_ExecResult) -> "ExecutionResult":
|
169
|
+
# Attribute access is defensive to tolerate ABI field name differences.
|
170
|
+
return cls(
|
171
|
+
out=getattr(r, "output", ""),
|
172
|
+
err=getattr(r, "error", ""),
|
173
|
+
exit_code=int(getattr(r, "exit_code", getattr(r, "exitCode", -1))),
|
174
|
+
success=bool(getattr(r, "success", False)),
|
175
|
+
execution_time=float(getattr(r, "execution_time", getattr(r, "executionTime", 0.0))),
|
176
|
+
)
|
177
|
+
|
178
|
+
|
179
|
+
# ---------- Public API ----------
|
180
|
+
class Shell:
|
181
|
+
"""Thin ergonomic wrapper around the C++ VirtualShell.
|
182
|
+
|
183
|
+
Notes:
|
184
|
+
- No Python-side I/O; all execution flows delegate to the C++ backend.
|
185
|
+
- All timeouts are best-effort and enforced by the backend. A timeout typically
|
186
|
+
returns `exit_code == -1` and `success == False` with an error message.
|
187
|
+
- Methods that accept `as_dataclass` can return the raw C++ result for callers
|
188
|
+
that want to avoid extra allocations/mapping.
|
189
|
+
"""
|
190
|
+
|
191
|
+
def __init__(
|
192
|
+
self,
|
193
|
+
powershell_path: Optional[str] = None,
|
194
|
+
working_directory: Optional[Union[str, Path]] = None,
|
195
|
+
timeout_seconds: float = 5.0,
|
196
|
+
environment: Optional[Dict[str, str]] = None,
|
197
|
+
initial_commands: Optional[List[str]] = None,
|
198
|
+
cpp_module: Any = None,
|
199
|
+
) -> None:
|
200
|
+
"""Configure a new Shell instance.
|
201
|
+
|
202
|
+
Parameters
|
203
|
+
----------
|
204
|
+
powershell_path : Optional[str]
|
205
|
+
Explicit path to `pwsh`/`powershell`. If omitted, the backend resolves it.
|
206
|
+
working_directory : Optional[Union[str, Path]]
|
207
|
+
Working directory for the child process. Resolved to an absolute path.
|
208
|
+
timeout_seconds : float
|
209
|
+
Default per-command timeout used when a method's `timeout` is not provided.
|
210
|
+
environment : Optional[Dict[str, str]]
|
211
|
+
Extra environment variables for the child process.
|
212
|
+
initial_commands : Optional[List[str]]
|
213
|
+
Commands that the backend will issue on process start (e.g., encoding setup).
|
214
|
+
cpp_module : Any
|
215
|
+
For testing/DI: provide a custom module exposing the C++ API surface.
|
216
|
+
"""
|
217
|
+
mod = cpp_module or _CPP_MODULE
|
218
|
+
cfg = mod.Config()
|
219
|
+
if powershell_path:
|
220
|
+
cfg.powershell_path = str(powershell_path)
|
221
|
+
if working_directory:
|
222
|
+
cfg.working_directory = str(Path(working_directory).resolve())
|
223
|
+
cfg.timeout_seconds = int(timeout_seconds or 0)
|
224
|
+
|
225
|
+
if environment:
|
226
|
+
# Copy to detach from caller's dict and avoid accidental mutation.
|
227
|
+
cfg.environment = dict(environment)
|
228
|
+
if initial_commands:
|
229
|
+
# Force string-ification to prevent surprises from non-str types.
|
230
|
+
cfg.initial_commands = list(map(str, initial_commands))
|
231
|
+
|
232
|
+
self._cfg: _CPP_Config = cfg
|
233
|
+
self._core: _CPP_VirtualShell = mod.VirtualShell(cfg)
|
234
|
+
|
235
|
+
def start(self) -> "Shell":
|
236
|
+
"""Start (or confirm) the backend PowerShell process.
|
237
|
+
|
238
|
+
Returns self for fluent chaining.
|
239
|
+
Raises `PowerShellNotFoundError` if the process cannot be started.
|
240
|
+
"""
|
241
|
+
if self._core.is_alive():
|
242
|
+
return self
|
243
|
+
if self._core.start():
|
244
|
+
return self
|
245
|
+
|
246
|
+
# Backend could not start the process; provide a precise error.
|
247
|
+
raise PowerShellNotFoundError(
|
248
|
+
f"Failed to start PowerShell process. Path: '{self._cfg.powershell_path or 'pwsh/powershell'}'"
|
249
|
+
)
|
250
|
+
|
251
|
+
def stop(self, force: bool = False) -> None:
|
252
|
+
"""Stop the backend process.
|
253
|
+
|
254
|
+
`force=True` requests an immediate termination (backend-specific semantics).
|
255
|
+
Always safe to call; errors are wrapped in `SmartShellError`.
|
256
|
+
"""
|
257
|
+
try:
|
258
|
+
self._core.stop(force)
|
259
|
+
except Exception as e: # Surface backend failures in a consistent type.
|
260
|
+
raise VirtualShellError(f"Failed to stop PowerShell: {e}") from e
|
261
|
+
|
262
|
+
@property
|
263
|
+
def is_running(self) -> bool:
|
264
|
+
"""Return True if the backend process is alive."""
|
265
|
+
return bool(self._core.is_alive())
|
266
|
+
|
267
|
+
# -------- sync --------
|
268
|
+
def run(
|
269
|
+
self,
|
270
|
+
command: str,
|
271
|
+
timeout: Optional[float] = None,
|
272
|
+
*,
|
273
|
+
raise_on_error: bool = False,
|
274
|
+
as_dataclass: bool = True,
|
275
|
+
) -> Union[ExecutionResult, _CPP_ExecResult]:
|
276
|
+
"""Execute a single PowerShell command string.
|
277
|
+
|
278
|
+
Parameters
|
279
|
+
----------
|
280
|
+
command : str
|
281
|
+
Raw PowerShell command. Caller is responsible for quoting/sanitizing.
|
282
|
+
timeout : Optional[float]
|
283
|
+
Per-call timeout override in seconds; <= 0 means "no override".
|
284
|
+
raise_on_error : bool
|
285
|
+
If True, raise `ExecutionTimeoutError`/`ExecutionError` on failure.
|
286
|
+
as_dataclass : bool
|
287
|
+
If True, return an `ExecutionResult`; otherwise return the raw C++ result.
|
288
|
+
"""
|
289
|
+
to = _effective_timeout(timeout, self._cfg.timeout_seconds)
|
290
|
+
res: _CPP_ExecResult = self._core.execute(command=command, timeout_seconds=to)
|
291
|
+
_raise_on_failure(res, raise_on_error=raise_on_error, label="Command", timeout_used=to)
|
292
|
+
return ExecutionResult.from_cpp(res) if as_dataclass else res
|
293
|
+
|
294
|
+
def run_script(
|
295
|
+
self,
|
296
|
+
script_path: Union[str, Path],
|
297
|
+
args: Optional[Iterable[str]] = None,
|
298
|
+
timeout: Optional[float] = None,
|
299
|
+
*,
|
300
|
+
dot_source: bool = False,
|
301
|
+
raise_on_error: bool = False,
|
302
|
+
as_dataclass: bool = True,
|
303
|
+
) -> Union[ExecutionResult, _CPP_ExecResult]:
|
304
|
+
"""Execute a script file with positional arguments.
|
305
|
+
|
306
|
+
- `args` are passed as-is to the backend; quote appropriately for your script.
|
307
|
+
- `dot_source=True` runs in the current context (if supported by the backend),
|
308
|
+
which can mutate session state. Use with care.
|
309
|
+
- `raise_on_error` only affects Python-side exception raising; the backend
|
310
|
+
always runs with `raise_on_error=False` to avoid double-throwing.
|
311
|
+
"""
|
312
|
+
to = _effective_timeout(timeout, self._cfg.timeout_seconds)
|
313
|
+
res: _CPP_ExecResult = self._core.execute_script(
|
314
|
+
script_path=str(Path(script_path).resolve()),
|
315
|
+
args=list(args or []),
|
316
|
+
timeout_seconds=to,
|
317
|
+
dot_source=bool(dot_source),
|
318
|
+
raise_on_error=False,
|
319
|
+
)
|
320
|
+
_raise_on_failure(res, raise_on_error=raise_on_error, label="Script", timeout_used=to)
|
321
|
+
return ExecutionResult.from_cpp(res) if as_dataclass else res
|
322
|
+
|
323
|
+
def run_script_kv(
|
324
|
+
self,
|
325
|
+
script_path: Union[str, Path],
|
326
|
+
named_args: Optional[Dict[str, str]] = None,
|
327
|
+
timeout: Optional[float] = None,
|
328
|
+
*,
|
329
|
+
dot_source: bool = False,
|
330
|
+
raise_on_error: bool = False,
|
331
|
+
as_dataclass: bool = True,
|
332
|
+
) -> Union[ExecutionResult, _CPP_ExecResult]:
|
333
|
+
"""Execute a script file with *named* arguments.
|
334
|
+
|
335
|
+
`named_args` is copied to detach from caller mutations. Keys/values must be
|
336
|
+
strings representable in the PowerShell context (caller ensures quoting).
|
337
|
+
"""
|
338
|
+
to = _effective_timeout(timeout, self._cfg.timeout_seconds)
|
339
|
+
res: _CPP_ExecResult = self._core.execute_script_kv(
|
340
|
+
script_path=str(Path(script_path).resolve()),
|
341
|
+
named_args=dict(named_args or {}),
|
342
|
+
timeout_seconds=to,
|
343
|
+
dot_source=bool(dot_source),
|
344
|
+
raise_on_error=False,
|
345
|
+
)
|
346
|
+
_raise_on_failure(res, raise_on_error=raise_on_error, label="ScriptKV", timeout_used=to)
|
347
|
+
return ExecutionResult.from_cpp(res) if as_dataclass else res
|
348
|
+
|
349
|
+
def run_batch(
|
350
|
+
self,
|
351
|
+
commands: Iterable[str],
|
352
|
+
*,
|
353
|
+
per_command_timeout: Optional[float] = None,
|
354
|
+
stop_on_first_error: bool = True,
|
355
|
+
as_dataclass: bool = True,
|
356
|
+
) -> List[Union[ExecutionResult, _CPP_ExecResult]]:
|
357
|
+
"""Execute multiple commands sequentially in the same session.
|
358
|
+
|
359
|
+
- `per_command_timeout` applies to each individual command.
|
360
|
+
- `stop_on_first_error` semantics are enforced by the backend.
|
361
|
+
- Returns a list of results preserving the order of input commands.
|
362
|
+
"""
|
363
|
+
to = _effective_timeout(per_command_timeout, self._cfg.timeout_seconds)
|
364
|
+
vec = self._core.execute_batch(
|
365
|
+
commands=list(commands),
|
366
|
+
timeout_seconds=to,
|
367
|
+
)
|
368
|
+
if as_dataclass:
|
369
|
+
return [ExecutionResult.from_cpp(r) for r in vec]
|
370
|
+
return vec
|
371
|
+
|
372
|
+
def run_async(self, command: str, callback: Optional[Callable[[ExecutionResult], None]] = None, *, as_dataclass: bool = True):
|
373
|
+
"""Asynchronously execute a single command.
|
374
|
+
|
375
|
+
- If `callback` is provided, it is invoked on completion with the result type
|
376
|
+
controlled by `as_dataclass`.
|
377
|
+
- Returns a `concurrent.futures.Future` from the backend; if `as_dataclass` is True,
|
378
|
+
the returned future is a mapped proxy that yields `ExecutionResult`.
|
379
|
+
- Exceptions in your callback are swallowed to avoid breaking the executor.
|
380
|
+
"""
|
381
|
+
def _cb(py_res: _CPP_ExecResult) -> None:
|
382
|
+
if callback is None:
|
383
|
+
return
|
384
|
+
try:
|
385
|
+
callback(ExecutionResult.from_cpp(py_res) if as_dataclass else py_res)
|
386
|
+
except Exception:
|
387
|
+
# Intentionally ignore to keep the executor stable.
|
388
|
+
pass
|
389
|
+
|
390
|
+
c_fut = self._core.execute_async(command=command, callback=_cb if callback else None)
|
391
|
+
return _map_future(c_fut, lambda r: ExecutionResult.from_cpp(r)) if as_dataclass else c_fut
|
392
|
+
|
393
|
+
def run_async_batch(
|
394
|
+
self,
|
395
|
+
commands: Iterable[str],
|
396
|
+
progress: Optional[Callable[[ _CPP_BatchProg ], None]] = None,
|
397
|
+
*,
|
398
|
+
per_command_timeout: Optional[float] = None,
|
399
|
+
stop_on_first_error: bool = True,
|
400
|
+
as_dataclass: bool = True,
|
401
|
+
):
|
402
|
+
"""Asynchronously execute a batch of commands.
|
403
|
+
|
404
|
+
- `progress` is a pass-through callback from the backend for per-command updates.
|
405
|
+
- Returns a Future resolving to a list of results. Mapping to `ExecutionResult`
|
406
|
+
is applied if `as_dataclass` is True.
|
407
|
+
"""
|
408
|
+
to = _effective_timeout(per_command_timeout, self._cfg.timeout_seconds)
|
409
|
+
fut = self._core.execute_async_batch(
|
410
|
+
commands=list(commands),
|
411
|
+
progress_callback=progress if progress else None,
|
412
|
+
stop_on_first_error=bool(stop_on_first_error),
|
413
|
+
per_command_timeout_seconds=to,
|
414
|
+
)
|
415
|
+
if as_dataclass:
|
416
|
+
return _map_future(fut, lambda vec: [ExecutionResult.from_cpp(r) for r in vec])
|
417
|
+
return fut
|
418
|
+
|
419
|
+
def run_async_script(
|
420
|
+
self,
|
421
|
+
script_path: Union[str, Path],
|
422
|
+
args: Optional[Iterable[str]] = None,
|
423
|
+
callback: Optional[Callable[[ExecutionResult], None]] = None,
|
424
|
+
*,
|
425
|
+
timeout: Optional[float] = None,
|
426
|
+
dot_source: bool = False,
|
427
|
+
as_dataclass: bool = True,
|
428
|
+
):
|
429
|
+
"""Asynchronously execute a script with positional args.
|
430
|
+
|
431
|
+
- `callback` is invoked (if provided) upon completion. Exceptions inside
|
432
|
+
the callback are suppressed to protect the executor.
|
433
|
+
- Returns a Future that yields either the raw C++ result or `ExecutionResult`.
|
434
|
+
"""
|
435
|
+
def _cb(py_res: _CPP_ExecResult) -> None:
|
436
|
+
if callback is None:
|
437
|
+
return
|
438
|
+
try:
|
439
|
+
callback(ExecutionResult.from_cpp(py_res) if as_dataclass else py_res)
|
440
|
+
except Exception:
|
441
|
+
pass
|
442
|
+
|
443
|
+
to = _effective_timeout(timeout, self._cfg.timeout_seconds)
|
444
|
+
fut = self._core.execute_async_script(
|
445
|
+
script_path=str(Path(script_path).resolve()),
|
446
|
+
args=list(args or []),
|
447
|
+
callback=_cb if callback else None,
|
448
|
+
timeout_seconds=to,
|
449
|
+
dot_source=bool(dot_source),
|
450
|
+
raise_on_error=False,
|
451
|
+
)
|
452
|
+
if as_dataclass:
|
453
|
+
return _map_future(fut, lambda r: ExecutionResult.from_cpp(r))
|
454
|
+
return fut
|
455
|
+
|
456
|
+
def run_async_script_kv(
|
457
|
+
self,
|
458
|
+
script_path: Union[str, Path],
|
459
|
+
named_args: Optional[Dict[str, str]] = None,
|
460
|
+
callback: Optional[Callable[[ExecutionResult], None]] = None,
|
461
|
+
*,
|
462
|
+
timeout: Optional[float] = None,
|
463
|
+
dot_source: bool = False,
|
464
|
+
as_dataclass: bool = True,
|
465
|
+
):
|
466
|
+
"""Asynchronously execute a script with named args.
|
467
|
+
|
468
|
+
If `callback` is provided, it is wired to the returned Future using
|
469
|
+
`add_done_callback` and receives the mapped result when available.
|
470
|
+
"""
|
471
|
+
to = _effective_timeout(timeout, self._cfg.timeout_seconds)
|
472
|
+
fut = self._core.execute_async_script_kv(
|
473
|
+
script_path=str(Path(script_path).resolve()),
|
474
|
+
named_args=dict(named_args or {}),
|
475
|
+
timeout_seconds=to,
|
476
|
+
dot_source=bool(dot_source),
|
477
|
+
raise_on_error=False,
|
478
|
+
)
|
479
|
+
if callback:
|
480
|
+
def _done(f: cf.Future) -> None:
|
481
|
+
try:
|
482
|
+
py_res = f.result()
|
483
|
+
callback(ExecutionResult.from_cpp(py_res) if as_dataclass else py_res)
|
484
|
+
except Exception:
|
485
|
+
# Suppress to avoid breaking the executor.
|
486
|
+
pass
|
487
|
+
try:
|
488
|
+
fut.add_done_callback(_done)
|
489
|
+
except Exception:
|
490
|
+
# If the backend future doesn't support callbacks, silently continue.
|
491
|
+
pass
|
492
|
+
if as_dataclass:
|
493
|
+
return _map_future(fut, lambda r: ExecutionResult.from_cpp(r))
|
494
|
+
return fut
|
495
|
+
|
496
|
+
# -------- convenience --------
|
497
|
+
def pwsh(self, s: str, timeout: Optional[float] = None, raise_on_error: bool = False) -> ExecutionResult:
|
498
|
+
"""Execute a **literal** PowerShell string safely.
|
499
|
+
|
500
|
+
Example:
|
501
|
+
`shell.pwsh("Hello 'World'")` -> runs `Write-Output 'Hello ''World'''` semantics;
|
502
|
+
here we only quote the literal; you still provide the full command.
|
503
|
+
"""
|
504
|
+
return self.run(quote_pwsh_literal(s), timeout=timeout, raise_on_error=raise_on_error)
|
505
|
+
|
506
|
+
def __enter__(self) -> "Shell":
|
507
|
+
"""Context manager entry: ensure backend is running."""
|
508
|
+
if not self._core.is_alive():
|
509
|
+
self.start()
|
510
|
+
return self
|
511
|
+
|
512
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
513
|
+
"""Context manager exit: stop backend regardless of errors in the block."""
|
514
|
+
self.stop()
|
515
|
+
return None
|
@@ -0,0 +1,461 @@
|
|
1
|
+
Metadata-Version: 2.2
|
2
|
+
Name: virtualshell
|
3
|
+
Version: 1.0.0
|
4
|
+
Summary: High-performance PowerShell bridge (C++ pybind11 backend)
|
5
|
+
Keywords: powershell,automation,shell,cpp,pybind11
|
6
|
+
Author: Kim-Andre Myrvold
|
7
|
+
License: Apache License
|
8
|
+
Version 2.0, January 2004
|
9
|
+
http://www.apache.org/licenses/
|
10
|
+
|
11
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
12
|
+
|
13
|
+
1. Definitions.
|
14
|
+
|
15
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
16
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
17
|
+
|
18
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
19
|
+
the copyright owner that is granting the License.
|
20
|
+
|
21
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
22
|
+
other entities that control, are controlled by, or are under common
|
23
|
+
control with that entity. For the purposes of this definition,
|
24
|
+
"control" means (i) the power, direct or indirect, to cause the
|
25
|
+
direction or management of such entity, whether by contract or
|
26
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
27
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
28
|
+
|
29
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
30
|
+
exercising permissions granted by this License.
|
31
|
+
|
32
|
+
"Source" form shall mean the preferred form for making modifications,
|
33
|
+
including but not limited to software source code, documentation
|
34
|
+
source, and configuration files.
|
35
|
+
|
36
|
+
"Object" form shall mean any form resulting from mechanical
|
37
|
+
transformation or translation of a Source form, including but
|
38
|
+
not limited to compiled object code, generated documentation,
|
39
|
+
and conversions to other media types.
|
40
|
+
|
41
|
+
"Work" shall mean the work of authorship, whether in Source or
|
42
|
+
Object form, made available under the License, as indicated by a
|
43
|
+
copyright notice that is included in or attached to the work
|
44
|
+
(an example is provided in the Appendix below).
|
45
|
+
|
46
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
47
|
+
form, that is based on (or derived from) the Work and for which the
|
48
|
+
editorial revisions, annotations, elaborations, or other modifications
|
49
|
+
represent, as a whole, an original work of authorship. For the purposes
|
50
|
+
of this License, Derivative Works shall not include works that remain
|
51
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
52
|
+
the Work and Derivative Works thereof.
|
53
|
+
|
54
|
+
"Contribution" shall mean any work of authorship, including
|
55
|
+
the original version of the Work and any modifications or additions
|
56
|
+
to that Work or Derivative Works thereof, that is intentionally
|
57
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
58
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
59
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
60
|
+
means any form of electronic, verbal, or written communication sent
|
61
|
+
to the Licensor or its representatives, including but not limited to
|
62
|
+
communication on electronic mailing lists, source code control systems,
|
63
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
64
|
+
Licensor for the purpose of discussing and improving the Work, but
|
65
|
+
excluding communication that is conspicuously marked or otherwise
|
66
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
67
|
+
|
68
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
69
|
+
on behalf of whom a Contribution has been received by Licensor and
|
70
|
+
subsequently incorporated within the Work.
|
71
|
+
|
72
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
73
|
+
this License, each Contributor hereby grants to You a perpetual,
|
74
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
75
|
+
copyright license to reproduce, prepare Derivative Works of,
|
76
|
+
publicly display, publicly perform, sublicense, and distribute the
|
77
|
+
Work and such Derivative Works in Source or Object form.
|
78
|
+
|
79
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
80
|
+
this License, each Contributor hereby grants to You a perpetual,
|
81
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
82
|
+
(except as stated in this section) patent license to make, have made,
|
83
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
84
|
+
where such license applies only to those patent claims licensable
|
85
|
+
by such Contributor that are necessarily infringed by their
|
86
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
87
|
+
with the Work to which such Contribution(s) was submitted. If You
|
88
|
+
institute patent litigation against any entity (including a
|
89
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
90
|
+
or a Contribution incorporated within the Work constitutes direct
|
91
|
+
or contributory patent infringement, then any patent licenses
|
92
|
+
granted to You under this License for that Work shall terminate
|
93
|
+
as of the date such litigation is filed.
|
94
|
+
|
95
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
96
|
+
Work or Derivative Works thereof in any medium, with or without
|
97
|
+
modifications, and in Source or Object form, provided that You
|
98
|
+
meet the following conditions:
|
99
|
+
|
100
|
+
(a) You must give any other recipients of the Work or
|
101
|
+
Derivative Works a copy of this License; and
|
102
|
+
|
103
|
+
(b) You must cause any modified files to carry prominent notices
|
104
|
+
stating that You changed the files; and
|
105
|
+
|
106
|
+
(c) You must retain, in the Source form of any Derivative Works
|
107
|
+
that You distribute, all copyright, patent, trademark, and
|
108
|
+
attribution notices from the Source form of the Work,
|
109
|
+
excluding those notices that do not pertain to any part of
|
110
|
+
the Derivative Works; and
|
111
|
+
|
112
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
113
|
+
distribution, then any Derivative Works that You distribute must
|
114
|
+
include a readable copy of the attribution notices contained
|
115
|
+
within such NOTICE file, excluding those notices that do not
|
116
|
+
pertain to any part of the Derivative Works, in at least one
|
117
|
+
of the following places: within a NOTICE text file distributed
|
118
|
+
as part of the Derivative Works; within the Source form or
|
119
|
+
documentation, if provided along with the Derivative Works; or,
|
120
|
+
within a display generated by the Derivative Works, if and
|
121
|
+
wherever such third-party notices normally appear. The contents
|
122
|
+
of the NOTICE file are for informational purposes only and
|
123
|
+
do not modify the License. You may add Your own attribution
|
124
|
+
notices within Derivative Works that You distribute, alongside
|
125
|
+
or as an addendum to the NOTICE text from the Work, provided
|
126
|
+
that such additional attribution notices cannot be construed
|
127
|
+
as modifying the License.
|
128
|
+
|
129
|
+
You may add Your own copyright statement to Your modifications and
|
130
|
+
may provide additional or different license terms and conditions
|
131
|
+
for use, reproduction, or distribution of Your modifications, or
|
132
|
+
for any such Derivative Works as a whole, provided Your use,
|
133
|
+
reproduction, and distribution of the Work otherwise complies with
|
134
|
+
the conditions stated in this License.
|
135
|
+
|
136
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
137
|
+
any Contribution intentionally submitted for inclusion in the Work
|
138
|
+
by You to the Licensor shall be under the terms and conditions of
|
139
|
+
this License, without any additional terms or conditions.
|
140
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
141
|
+
the terms of any separate license agreement you may have executed
|
142
|
+
with Licensor regarding such Contributions.
|
143
|
+
|
144
|
+
6. Trademarks. This License does not grant permission to use the trade
|
145
|
+
names, trademarks, service marks, or product names of the Licensor,
|
146
|
+
except as required for reasonable and customary use in describing the
|
147
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
148
|
+
|
149
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
150
|
+
agreed to in writing, Licensor provides the Work (and each
|
151
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
152
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
153
|
+
implied, including, without limitation, any warranties or conditions
|
154
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
155
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
156
|
+
appropriateness of using or redistributing the Work and assume any
|
157
|
+
risks associated with Your exercise of permissions under this License.
|
158
|
+
|
159
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
160
|
+
whether in tort (including negligence), contract, or otherwise,
|
161
|
+
unless required by applicable law (such as deliberate and grossly
|
162
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
163
|
+
liable to You for damages, including any direct, indirect, special,
|
164
|
+
incidental, or consequential damages of any character arising as a
|
165
|
+
result of this License or out of the use or inability to use the
|
166
|
+
Work (including but not limited to damages for loss of goodwill,
|
167
|
+
work stoppage, computer failure or malfunction, or any and all
|
168
|
+
other commercial damages or losses), even if such Contributor
|
169
|
+
has been advised of the possibility of such damages.
|
170
|
+
|
171
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
172
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
173
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
174
|
+
or other liability obligations and/or rights consistent with this
|
175
|
+
License. However, in accepting such obligations, You may act only
|
176
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
177
|
+
of any other Contributor, and only if You agree to indemnify,
|
178
|
+
defend, and hold each Contributor harmless for any liability
|
179
|
+
incurred by, or claims asserted against, such Contributor by reason
|
180
|
+
of your accepting any such warranty or additional liability.
|
181
|
+
|
182
|
+
END OF TERMS AND CONDITIONS
|
183
|
+
|
184
|
+
APPENDIX: How to apply the Apache License to your work.
|
185
|
+
|
186
|
+
To apply the Apache License to your work, attach the following
|
187
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
188
|
+
replaced with your own identifying information. (Don't include
|
189
|
+
the brackets!) The text should be enclosed in the appropriate
|
190
|
+
comment syntax for the file format. We also recommend that a
|
191
|
+
file or class name and description of purpose be included on the
|
192
|
+
same "printed page" as the copyright notice for easier
|
193
|
+
identification within third-party archives.
|
194
|
+
|
195
|
+
Copyright 2025 Kim-Andre Myrvold
|
196
|
+
|
197
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
198
|
+
you may not use this file except in compliance with the License.
|
199
|
+
You may obtain a copy of the License at
|
200
|
+
|
201
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
202
|
+
|
203
|
+
Unless required by applicable law or agreed to in writing, software
|
204
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
205
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
206
|
+
See the License for the specific language governing permissions and
|
207
|
+
limitations under the License.
|
208
|
+
|
209
|
+
Classifier: Programming Language :: Python :: 3
|
210
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
211
|
+
Classifier: Programming Language :: C++
|
212
|
+
Classifier: Operating System :: Microsoft :: Windows
|
213
|
+
Classifier: Operating System :: POSIX :: Linux
|
214
|
+
Classifier: License :: OSI Approved :: MIT License
|
215
|
+
Project-URL: Homepage, https://github.com/Chamoswor/virtualshell
|
216
|
+
Project-URL: Issues, https://github.com/Chamoswor/virtualshell/issues
|
217
|
+
Requires-Python: >=3.8
|
218
|
+
Description-Content-Type: text/markdown
|
219
|
+
|
220
|
+
````markdown
|
221
|
+
# virtualshell
|
222
|
+
|
223
|
+
High-performance Python façade over a **C++ PowerShell runner**.
|
224
|
+
A single long-lived PowerShell process is managed in C++, handling pipes, threads, timeouts and output demux; Python exposes a small, predictable API.
|
225
|
+
|
226
|
+
---
|
227
|
+
|
228
|
+
## Features
|
229
|
+
|
230
|
+
- **Persistent session** to `pwsh`/`powershell` (reuse modules, `$env:*`, functions, cwd)
|
231
|
+
- **Sync & async** execution (Futures + optional callbacks)
|
232
|
+
- **Script execution** (positional / named args, optional dot-sourcing)
|
233
|
+
- **Batch** with per-command timeout & early-stop
|
234
|
+
- **Clear failures** (typed exceptions), **context manager** lifecycle
|
235
|
+
|
236
|
+
---
|
237
|
+
|
238
|
+
## Install
|
239
|
+
|
240
|
+
```bash
|
241
|
+
pip install virtualshell
|
242
|
+
````
|
243
|
+
|
244
|
+
### Supported platforms
|
245
|
+
|
246
|
+
* **Windows 10/11 x64**
|
247
|
+
* **Linux**: x86_64 and aarch64 (manylinux_2_28 / glibc ≥ 2.28)
|
248
|
+
* **macOS**: 12+ (x86_64 and arm64)
|
249
|
+
* **Python**: 3.8 – 3.13
|
250
|
+
|
251
|
+
> Requires PowerShell on `PATH` (`pwsh` preferred, `powershell` also supported).
|
252
|
+
|
253
|
+
---
|
254
|
+
|
255
|
+
## Quick start
|
256
|
+
|
257
|
+
```python
|
258
|
+
import virtualshell
|
259
|
+
|
260
|
+
# Create a shell with a 5s default timeout
|
261
|
+
sh = virtualshell.Shell(timeout_seconds=5).start()
|
262
|
+
|
263
|
+
# 1) One-liners (sync)
|
264
|
+
res = sh.run("Write-Output 'hello'")
|
265
|
+
print(res.out.strip()) # -> hello
|
266
|
+
|
267
|
+
# 2) Async single command
|
268
|
+
fut = sh.run_async("Write-Output 'async!'")
|
269
|
+
print(fut.result().out.strip())
|
270
|
+
|
271
|
+
# 3) Scripts with positional args
|
272
|
+
r = sh.run_script(r"C:\temp\demo.ps1", args=["alpha", "42"])
|
273
|
+
print(r.out)
|
274
|
+
|
275
|
+
# 4) Scripts with named args
|
276
|
+
r = sh.run_script_kv(r"C:\temp\demo.ps1", named_args={"Name":"Alice","Count":"3"})
|
277
|
+
print(r.out)
|
278
|
+
|
279
|
+
# 5) Context manager (auto-stop on exit)
|
280
|
+
with virtualshell.Shell(timeout_seconds=3) as s:
|
281
|
+
print(s.run("Write-Output 'inside with'").out.strip())
|
282
|
+
|
283
|
+
sh.stop()
|
284
|
+
```
|
285
|
+
|
286
|
+
Another example (stateful session):
|
287
|
+
|
288
|
+
```python
|
289
|
+
from virtualshell import Shell
|
290
|
+
with Shell(timeout_seconds=3) as sh:
|
291
|
+
sh.run("function Inc { $global:i++; $global:i }")
|
292
|
+
nums = [sh.run("Inc").out.strip() for _ in range(5)]
|
293
|
+
print(nums) # ['1','2','3','4','5']
|
294
|
+
```
|
295
|
+
|
296
|
+
---
|
297
|
+
|
298
|
+
## API (overview)
|
299
|
+
|
300
|
+
```python
|
301
|
+
import virtualshell
|
302
|
+
from virtualshell import ExecutionResult # dataclass view
|
303
|
+
|
304
|
+
sh = virtualshell.Shell(
|
305
|
+
powershell_path=None, # optional explicit path
|
306
|
+
working_directory=None, # resolved to absolute path
|
307
|
+
timeout_seconds=5.0, # default per-command timeout
|
308
|
+
environment={"FOO": "BAR"}, # extra child env vars
|
309
|
+
initial_commands=["$ErrorActionPreference='Stop'"], # post-start setup
|
310
|
+
).start()
|
311
|
+
|
312
|
+
# Sync
|
313
|
+
res: ExecutionResult = sh.run("Get-Location | Select-Object -Expand Path")
|
314
|
+
|
315
|
+
# Scripts
|
316
|
+
res = sh.run_script(r"/path/to/job.ps1", args=["--fast","1"])
|
317
|
+
res = sh.run_script_kv(r"/path/to/job.ps1", named_args={"Mode":"Fast","Count":"1"})
|
318
|
+
res = sh.run_script(r"/path/init.ps1", dot_source=True)
|
319
|
+
|
320
|
+
# Async
|
321
|
+
f = sh.run_async("Write-Output 'ping'")
|
322
|
+
f2 = sh.run_async_batch(["$PSVersionTable", "Get-Random"])
|
323
|
+
|
324
|
+
# Convenience
|
325
|
+
res = sh.pwsh("literal 'quoted' string") # safe single-quoted literal
|
326
|
+
|
327
|
+
sh.stop()
|
328
|
+
```
|
329
|
+
|
330
|
+
### Return type
|
331
|
+
|
332
|
+
By default you get a Python dataclass:
|
333
|
+
|
334
|
+
```python
|
335
|
+
@dataclass(frozen=True)
|
336
|
+
class ExecutionResult:
|
337
|
+
output: str
|
338
|
+
error: str
|
339
|
+
exit_code: int
|
340
|
+
success: bool
|
341
|
+
execution_time: float
|
342
|
+
```
|
343
|
+
|
344
|
+
Pass `as_dataclass=False` to receive the raw C++ result object.
|
345
|
+
|
346
|
+
### Timeouts
|
347
|
+
|
348
|
+
* Every method accepts a `timeout` (or `per_command_timeout`) in seconds.
|
349
|
+
* On timeout: `success=False`, `exit_code=-1`, `error` contains `"timeout"`.
|
350
|
+
* Async futures resolve with the timeout result; late output is dropped in C++.
|
351
|
+
|
352
|
+
---
|
353
|
+
|
354
|
+
## Design notes
|
355
|
+
|
356
|
+
* **Thin wrapper:** heavy I/O in C++; Python does orchestration only.
|
357
|
+
* **No surprises:** stable API, documented side-effects.
|
358
|
+
* **Clear failure modes:** `raise_on_error` and typed exceptions.
|
359
|
+
* **Thread-friendly:** async returns Futures/callbacks; no Python GIL-level locking.
|
360
|
+
* **Boundary hygiene:** explicit path/arg conversions, minimal marshalling.
|
361
|
+
|
362
|
+
### Security
|
363
|
+
|
364
|
+
* The wrapper **does not sanitize** raw commands. Only `pwsh()` applies literal single-quoting for data.
|
365
|
+
* Don’t pass untrusted strings to `run*` without proper quoting/sanitization.
|
366
|
+
* Avoid logging secrets; env injection happens via `Shell(..., environment=...)`.
|
367
|
+
|
368
|
+
### Performance
|
369
|
+
|
370
|
+
* Sync/async routes call into C++ directly; Python overhead is object creation + callback dispatch.
|
371
|
+
* Prefer **batch/async** for many small commands to amortize round-trips.
|
372
|
+
|
373
|
+
### Lifetime
|
374
|
+
|
375
|
+
* `Shell.start()` ensures a running backend; `Shell.stop()` tears it down.
|
376
|
+
* `with Shell(...)` guarantees stop-on-exit, even on exceptions.
|
377
|
+
|
378
|
+
---
|
379
|
+
|
380
|
+
## Exceptions
|
381
|
+
|
382
|
+
```python
|
383
|
+
from virtualshell.errors import (
|
384
|
+
VirtualShellError,
|
385
|
+
PowerShellNotFoundError,
|
386
|
+
ExecutionTimeoutError,
|
387
|
+
ExecutionError,
|
388
|
+
)
|
389
|
+
|
390
|
+
try:
|
391
|
+
res = sh.run("throw 'boom'", raise_on_error=True)
|
392
|
+
except ExecutionTimeoutError:
|
393
|
+
...
|
394
|
+
except ExecutionError as e:
|
395
|
+
print("PowerShell failed:", e)
|
396
|
+
```
|
397
|
+
|
398
|
+
* `ExecutionTimeoutError` is raised on timeouts **if** `raise_on_error=True`.
|
399
|
+
* Otherwise, APIs return `ExecutionResult(success=False)`.
|
400
|
+
|
401
|
+
---
|
402
|
+
|
403
|
+
## Configuration tips
|
404
|
+
|
405
|
+
If PowerShell isn’t on `PATH`, pass `powershell_path`:
|
406
|
+
|
407
|
+
```python
|
408
|
+
Shell(powershell_path=r"C:\Program Files\PowerShell\7\pwsh.exe")
|
409
|
+
```
|
410
|
+
|
411
|
+
Session setup example:
|
412
|
+
|
413
|
+
```python
|
414
|
+
Shell(initial_commands=[
|
415
|
+
"$OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::new()",
|
416
|
+
"$ErrorActionPreference = 'Stop'"
|
417
|
+
])
|
418
|
+
```
|
419
|
+
|
420
|
+
---
|
421
|
+
|
422
|
+
## Building from source (optional)
|
423
|
+
|
424
|
+
You normally won’t need this when using wheels.
|
425
|
+
|
426
|
+
**Prereqs:** Python ≥3.8, C++17, CMake ≥3.20, `scikit-build-core`, `pybind11`.
|
427
|
+
|
428
|
+
```bash
|
429
|
+
# in repo root
|
430
|
+
python -m pip install -U pip build
|
431
|
+
python -m build # -> dist/*.whl, dist/*.tar.gz
|
432
|
+
python -m pip install dist/virtualshell-*.whl
|
433
|
+
```
|
434
|
+
|
435
|
+
Editable install:
|
436
|
+
|
437
|
+
```bash
|
438
|
+
python -m pip install -e .
|
439
|
+
```
|
440
|
+
|
441
|
+
* Linux wheels target **manylinux_2_28** (x86_64/aarch64).
|
442
|
+
* macOS builds target **x86_64** and **arm64** (may be universal2).
|
443
|
+
|
444
|
+
---
|
445
|
+
|
446
|
+
## Roadmap
|
447
|
+
|
448
|
+
* ✅ Windows x64 wheels (3.8–3.13)
|
449
|
+
* ✅ Linux x64/aarch64 wheels (manylinux_2_28)
|
450
|
+
* ✅ macOS x86_64/arm64 wheels
|
451
|
+
* ⏳ Streaming APIs and richer progress events
|
452
|
+
|
453
|
+
---
|
454
|
+
|
455
|
+
## License
|
456
|
+
|
457
|
+
Apache 2.0 — see [LICENSE](LICENSE).
|
458
|
+
|
459
|
+
---
|
460
|
+
|
461
|
+
*Issues & feedback are welcome. Please include Python version, OS, your PowerShell path (`pwsh`/`powershell`), and a minimal repro.*
|
@@ -0,0 +1,9 @@
|
|
1
|
+
virtualshell/__init__.py,sha256=8PE1B8yiMyZg2gwG18EvXt2vDEflvBeAdh7mNn58-GE,912
|
2
|
+
virtualshell/_core.cpython-312-aarch64-linux-gnu.so,sha256=qL6EU_2X2HTZko2R1QyNYl9WzDVPYm8lvpZhFxEP26M,595664
|
3
|
+
virtualshell/_version.py,sha256=ZgAXEMjAMZx3cZroB6PgojYwdhTZjPbU5RqZEfdYQv0,17
|
4
|
+
virtualshell/errors.py,sha256=lWOmidPiGKLef_pB-gelAF-3UbgX9Tmvu0s7JgmOg_k,193
|
5
|
+
virtualshell/shell.py,sha256=iHEFnbY3ggR2G-VpxAHrP3RVx3nYy1S2VxxLUTLRHa4,20915
|
6
|
+
virtualshell-1.0.0.dist-info/METADATA,sha256=C0_uXHh7-Lxslvmqo8JBOW1M5gK8D1YieCEVQgWf21c,20087
|
7
|
+
virtualshell-1.0.0.dist-info/WHEEL,sha256=H_BrkKb82q8ut3CkSLoO5dMJTuGH92rAymvKuympuN8,159
|
8
|
+
virtualshell-1.0.0.dist-info/RECORD,,
|
9
|
+
virtualshell-1.0.0.dist-info/licenses/LICENSE,sha256=7RNZIZ-wB2I1pFb_4uWOXYStIFAwxbGLypaZuW-AKis,11347
|
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright 2025 Kim-Andre Myrvold
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|