@node-ctypes/python 0.1.1 → 0.2.0

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.
package/README.md CHANGED
@@ -1,214 +1,230 @@
1
- # node-python (`@node-ctypes/python`)
2
-
3
- Embed CPython in Node.js with a TypeScript API powered by
4
- [node-ctypes](https://www.npmjs.com/package/node-ctypes).
5
- This standalone ESM package ships compiled JavaScript and declarations.
6
- Python runs in-process, not in a subprocess or sandbox.
7
-
8
- ## Requirements and installation
9
-
10
- - Node.js 24+ and an ESM application.
11
- - Python 3.12+ with a shared library matching Node.js architecture and Python ABI.
12
- - Windows, Linux or macOS.
13
-
14
- Windows and macOS installations normally include the shared library. On
15
- Debian/Ubuntu install the matching `libpython3.x` package; with pyenv use
16
- `PYTHON_CONFIGURE_OPTS=--enable-shared`.
17
- Install optional Python dependencies into the selected interpreter's environment.
18
- Neither Python nor its packages are bundled.
19
-
20
- ```sh
21
- npm install @node-ctypes/python
22
- ```
23
-
24
- To build from source, run from this directory:
25
-
26
- ```sh
27
- npm install
28
- npm run build
29
- npm test
30
- npm pack
31
- ```
32
-
33
- Install the resulting tarball into your application with
34
- `npm install /path/to/node-ctypes-python-0.1.0.tgz`.
35
- The runtime dependency is published `node-ctypes` (`^2.10.0`); no custom native
36
- bridge, core patch or JavaScript worker is required.
37
-
38
- ## Quick start
39
-
40
- ```typescript
41
- import { Python, kwargs } from "@node-ctypes/python";
42
-
43
- const python = await Python.initialize({ stdin: false, stdout: "node", stderr: "node" });
44
- try {
45
- const math = await python.import("math");
46
- console.log(await math.sqrt(81)); // 9
47
-
48
- await python.exec("def add(a, b): return a + b");
49
- console.log(await python.main.add(20, 22)); // 42
50
-
51
- const json = await python.import("json");
52
- console.log(await json.dumps({ b: 2, a: 1 }, kwargs({ sort_keys: true })));
53
-
54
- python.module("node", { greet: (name: string) => `Hello ${name}` });
55
- await python.exec("import node\nprint(node.greet('Python'))");
56
- } finally {
57
- await python.finalize();
58
- }
59
- ```
60
-
61
- ### Configuration
62
-
63
- `Python.initialize({ executable, library, stdin, stdout, stderr, synchronousCallbacks, switchInterval })`
64
- returns the runtime singleton. Options apply to the first initialization.
65
-
66
- - `executable`, or `PYTHON`, selects the interpreter; an explicit choice never
67
- falls back. Otherwise discovery tries installed Python commands.
68
- - `library`, or `PYTHON_LIBRARY`, overrides shared-library discovery. The selected
69
- interpreter supplies `sys.path`, including virtualenv paths. Each discovery
70
- probe has a 10-second timeout.
71
- - `stdin: false` leaves standard input to Node.js. `stdout` and `stderr` accept
72
- `"inherit"` (default), `"node"` or a text callback.
73
- - `synchronousCallbacks: true` enables native callback dispatch during
74
- interruptible synchronous Python waits. It requires an available SIGURG wakeup
75
- on POSIX, or Windows Python 3.14+ with its interrupt event available.
76
- Unsupported configurations fail explicitly; the default is `false`.
77
- - `switchInterval` sets the GIL switch interval in milliseconds
78
- (`sys.setswitchinterval`). The default is `5`, as in CPython. Every Python call
79
- acquires the GIL on the Node.js thread, so while Python threads run CPU-bound
80
- code each call can stall the event loop for several intervals: on Windows we
81
- measured stalls of 150–250 ms with the default. `0.5` reduced them to under
82
- 50 ms, but slowed two contending CPU-bound Python threads by 40% or more.
83
- To keep the main thread free without that cost, host Python in a worker
84
- (`examples/worker.ts`).
85
-
86
- Native objects are always enabled; there is no `nativeObjects` mode.
87
- Free-threaded builds require their matching executable and shared library;
88
- an ABI3t compatibility DLL alone does not enable free threading.
89
-
90
- ## API and execution model
91
-
92
- | API | Purpose |
93
- | ------------------------------------------------ | ------------------------------------------------------ |
94
- | `Python.initialize(options)` | Initialize the singleton asynchronously |
95
- | `python.main`, `python.builtins` | Live module proxies |
96
- | `python.version`, `.executable`, `.library` | Selected interpreter information |
97
- | `await python.exec(code)` | Execute statements in `__main__` |
98
- | `await python.eval<T>(expression)` | Evaluate and deeply convert the result |
99
- | `await python.import<T>(name)` | Import a live module, including dotted names |
100
- | `python.module(name, members)` | Register JavaScript members as a Python module |
101
- | `python.toPython<T>(value)` | Create an explicitly disposable Python proxy |
102
- | `python.run(operation, { signal })` | Await a Python operation or awaitable, with abort |
103
- | `await python.with(manager, body)` / `asyncWith` | Run a context manager, including exception suppression |
104
- | `python.stats()` | Inspect shared-reference and scheduler counters |
105
- | `await python.finalize()` | Drain accepted native calls and close the runtime |
106
-
107
- Exports also include `PythonError`, `Tuple`, `kwargs`, `byReference` and
108
- `cancellable`. Types and generics describe the dynamic API; they do not validate
109
- Python types at runtime.
110
-
111
- **Calls are asynchronous; live access is synchronous.** Python functions, methods,
112
- classes and builtins return Promises, including `await new cls(...)`.
113
- Calls, imports, `exec` and `eval` execute on one Python-owned thread without
114
- occupying a waiting libuv worker. Arguments and results are converted on Node.js.
115
- Attributes, indices, assignment, enumeration, ordinary iteration, conversion and
116
- disposal remain synchronous and can block Node.js. Native initialization and
117
- finalization also run synchronously on the hosting Node.js thread.
118
-
119
- Python coroutine results are automatically awaited through a separate asyncio
120
- thread. Async iterators work in both directions. An async JavaScript callback
121
- must be awaited from Python; a synchronous Python callback cannot return a
122
- JavaScript Promise. `cancellable(fn)` adds an `AbortSignal` to callbacks that
123
- cooperate with Python cancellation.
124
-
125
- `python.run(operation, { signal })` accepts the Promise of a call, `exec`,
126
- `eval` or `import`, or a Python awaitable, and rejects with `signal.reason`
127
- on abort (`AbortSignal.timeout(ms)` for time limits). A queued operation is
128
- skipped; running Python code receives one `KeyboardInterrupt`, so `finally`
129
- blocks run and `except Exception` does not swallow it. On CPython 3.12 only,
130
- a one-line loop that starts a `try` block (`try:` followed by `while True: ...`)
131
- skips that `finally` when interrupted; put the loop body on its own line.
132
- Native calls are
133
- interrupted only when they return; asyncio work is cancelled. Synchronous proxy
134
- access and JavaScript work cannot be aborted.
135
-
136
- ### Values, memory and lifetime
137
-
138
- - Scalars convert naturally; Python integers outside JavaScript's safe range
139
- become bigints. Arrays, `Tuple`, objects/Maps and Sets copy to Python containers.
140
- Dates become UTC datetimes; Temporal conversions require runtime support.
141
- - Other Python objects remain live proxies. `eval()` and `proxy.toJS()` perform
142
- deep conversion; ordinary call results use shallow conversion. Circular copies
143
- are rejected; use live proxies or `byReference()` instead.
144
- - Arbitrary JavaScript instances remain shared references. `byReference(value)`
145
- also shares ordinary containers. Python attributes take precedence over dict keys.
146
- - Buffer/Uint8Array values copy to Python bytes; other typed arrays, ArrayBuffers
147
- and DataViews expose shared memoryviews. `byReference(buffer)` shares writable
148
- memory. `proxy.toTypedArray()` requires a C-contiguous Python buffer and copies
149
- read-only buffers. Do not detach, transfer or resize shared backing memory.
150
- - Release owned proxies with `[Symbol.dispose]()` when practical, including
151
- `PythonError.exception`. GC is nondeterministic. Disposal drops the reference
152
- immediately; on free-threaded builds CPython may run the object's destructor
153
- later, when the thread that created it next runs Python code. `PythonError` exposes `type`,
154
- `traceback`, `exception` and, when available, the original JavaScript `cause`.
155
-
156
- Only one JavaScript thread per process may host Python. A Node.js worker can
157
- isolate synchronous access and conversions, but must finalize before terminating.
158
- Wait for application work and Python threads before finalization; do not finalize
159
- inside a Python callback. Repeated finalization is harmless; restart and
160
- subinterpreters are not supported. Never use Python proxies or Python-backed
161
- memory afterward.
162
-
163
- Closing rejects new calls and drains accepted native operations, not every
164
- pending coroutine: remaining awaits are rejected during teardown. Cleanup also
165
- runs on normal `beforeExit`; `process.exit()` is not orderly finalization.
166
- Shutdown can wait for Python threads and has no overall timeout.
167
- Execute trusted Python code only.
168
-
169
- ## Examples and tests
170
-
171
- Run examples directly, for example `node examples/basics.ts`.
172
- They cover usage in more detail than this overview:
173
-
174
- | Example | Focus |
175
- | --------------------------------------------- | --------------------------------------------- |
176
- | [basics.ts](./examples/basics.ts) | Values, live objects, errors and conversions |
177
- | [callbacks.ts](./examples/callbacks.ts) | JavaScript callbacks and constructors |
178
- | [threads.ts](./examples/threads.ts) | Python threads and cross-thread callbacks |
179
- | [async.ts](./examples/async.ts) | Await, cancellation and async iteration |
180
- | [module.ts](./examples/module.ts) | JavaScript modules and local Python imports |
181
- | [worker.ts](./examples/worker.ts) | Hosting Python in a Node.js worker |
182
- | [cryptography.ts](./examples/cryptography.ts) | Python cryptography integration |
183
- | [lxml.ts](./examples/lxml.ts) | XML parsing, XPath, XSLT and canonicalization |
184
-
185
- Optional packages are needed only for the corresponding examples and must be
186
- installed in the selected interpreter. Set `PYTHON` to that executable if it
187
- differs from the one found automatically. The suite regression-tests callbacks
188
- and missing-package diagnostics; other example scenarios are manual.
189
-
190
- ```sh
191
- npm run typecheck
192
- npm test
193
- npm run test:unit
194
- npm run test:integration
195
- npm run test:types
196
- npm run test:backlog
197
- npm run test:stress
198
- ```
199
-
200
- `npm test` builds and runs the ordinary suite; integration tests require shared
201
- CPython. Typechecks include sources, examples and test helpers.
202
- `test:backlog` checks queued ownership, every outcome and shutdown under load.
203
- `test:stress` adds a 60-second mixed workload; set `NODE_PYTHON_STRESS_SECONDS`
204
- to change its duration. Both are opt-in, force GC in isolated children and report
205
- memory/latency diagnostics, not performance or leak-certification guarantees.
206
- The runtime does not impose application backpressure.
207
-
208
- The [CI workflow](./.github/workflows/ci.yml) runs `npm test` with Python
209
- 3.12, 3.13, 3.14, 3.14t and 3.15 on Windows, Linux and macOS. It is discovered only when
210
- this package is a repository root, not while nested in another repository.
211
- Pushing a `v<version>` tag that matches `package.json` publishes to npm once the
212
- whole matrix passes (npm Trusted Publishing; versions with a `-` go to `next`).
213
- For implementation diagrams and ownership invariants, see [FLOWS.md](./FLOWS.md)
214
- (Italian).
1
+ # node-python (`@node-ctypes/python`)
2
+
3
+ Embed CPython in Node.js with a TypeScript API powered by
4
+ [node-ctypes](https://www.npmjs.com/package/node-ctypes).
5
+ This standalone ESM package ships compiled JavaScript and declarations.
6
+ Python runs in-process, not in a subprocess or sandbox.
7
+
8
+ ## Requirements and installation
9
+
10
+ - Node.js 24+ and an ESM application.
11
+ - Python 3.12+ with a shared library matching Node.js architecture and Python ABI.
12
+ - Windows, Linux or macOS.
13
+
14
+ Windows and macOS installations normally include the shared library. On
15
+ Debian/Ubuntu install the matching `libpython3.x` package; with pyenv use
16
+ `PYTHON_CONFIGURE_OPTS=--enable-shared`.
17
+ Install optional Python dependencies into the selected interpreter's environment.
18
+ Neither Python nor its packages are bundled.
19
+
20
+ ```sh
21
+ npm install @node-ctypes/python
22
+ ```
23
+
24
+ To build from source, run from this directory:
25
+
26
+ ```sh
27
+ npm install
28
+ npm run build
29
+ npm test
30
+ npm pack
31
+ ```
32
+
33
+ Install the resulting tarball into your application with
34
+ `npm install /path/to/node-ctypes-python-0.1.0.tgz`.
35
+ The runtime dependency is published `node-ctypes` (`^2.10.0`); no custom native
36
+ bridge, core patch or JavaScript worker is required.
37
+
38
+ ## Quick start
39
+
40
+ ```typescript
41
+ import { Python, kwargs } from "@node-ctypes/python";
42
+
43
+ const python = await Python.initialize({ stdin: false, stdout: "node", stderr: "node" });
44
+ try {
45
+ const math = await python.import("math");
46
+ console.log(await math.sqrt(81)); // 9
47
+
48
+ await python.exec("def add(a, b): return a + b");
49
+ console.log(await python.main.add(20, 22)); // 42
50
+
51
+ const json = await python.import("json");
52
+ console.log(await json.dumps({ b: 2, a: 1 }, kwargs({ sort_keys: true })));
53
+
54
+ python.module("node", { greet: (name: string) => `Hello ${name}` });
55
+ await python.exec("import node\nprint(node.greet('Python'))");
56
+ } finally {
57
+ await python.finalize();
58
+ }
59
+ ```
60
+
61
+ ### Configuration
62
+
63
+ `Python.initialize({ executable, library, stdin, stdout, stderr, synchronousCallbacks, switchInterval })`
64
+ returns the runtime singleton. Options apply to the first initialization.
65
+
66
+ - `executable`, or `PYTHON`, selects the interpreter; an explicit choice never
67
+ falls back. Otherwise discovery tries installed Python commands.
68
+ - `library`, or `PYTHON_LIBRARY`, overrides shared-library discovery. The selected
69
+ interpreter supplies `sys.path`, including virtualenv paths. Each discovery
70
+ probe has a 10-second timeout.
71
+ - `stdin: false` leaves standard input to Node.js. `stdout` and `stderr` accept
72
+ `"inherit"` (default), `"node"`, `"console"` or a text callback. `"console"`
73
+ sends whole lines to `console.log` / `console.error` (a line without its newline
74
+ on `flush()` or at finalization). Without a console, as in an Electron renderer
75
+ or a packaged GUI app on Windows, Python's `sys.stdout` and `sys.stderr` are
76
+ `None` and `"inherit"` discards the output, as `pythonw` does: use `"console"`
77
+ (DevTools) or a callback (e.g. a log file).
78
+ - `synchronousCallbacks: true` enables native callback dispatch during
79
+ interruptible synchronous Python waits. It requires an available SIGURG wakeup
80
+ on POSIX, or Windows Python 3.14+ with its interrupt event available.
81
+ Unsupported configurations fail explicitly; the default is `false`.
82
+ - `switchInterval` sets the GIL switch interval in milliseconds
83
+ (`sys.setswitchinterval`). The default is `5`, as in CPython. Every Python call
84
+ acquires the GIL on the Node.js thread, so while Python threads run CPU-bound
85
+ code each call can stall the event loop for several intervals: on Windows we
86
+ measured stalls of 150–250 ms with the default. `0.5` reduced them to under
87
+ 50 ms, but slowed two contending CPU-bound Python threads by 40% or more.
88
+ To keep the main thread free without that cost, host Python in a worker
89
+ (`examples/worker.ts`).
90
+
91
+ Native objects are always enabled; there is no `nativeObjects` mode.
92
+ Free-threaded builds require their matching executable and shared library;
93
+ an ABI3t compatibility DLL alone does not enable free threading.
94
+
95
+ ## API and execution model
96
+
97
+ | API | Purpose |
98
+ | ------------------------------------------------ | ------------------------------------------------------ |
99
+ | `Python.initialize(options)` | Initialize the singleton asynchronously |
100
+ | `python.main`, `python.builtins` | Live module proxies |
101
+ | `python.version`, `.executable`, `.library` | Selected interpreter information |
102
+ | `await python.exec(code)` | Execute statements in `__main__` |
103
+ | `await python.eval<T>(expression)` | Evaluate and deeply convert the result |
104
+ | `await python.import<T>(name)` | Import a live module, including dotted names |
105
+ | `python.module(name, members)` | Register JavaScript members as a Python module |
106
+ | `python.toPython<T>(value)` | Create an explicitly disposable Python proxy |
107
+ | `python.run(operation, { signal })` | Await a Python operation or awaitable, with abort |
108
+ | `await python.with(manager, body)` / `asyncWith` | Run a context manager, including exception suppression |
109
+ | `python.stats()` | Inspect shared-reference and scheduler counters |
110
+ | `await python.finalize()` | Drain accepted native calls and close the runtime |
111
+
112
+ Exports also include `PythonError`, `Tuple`, `kwargs`, `byReference` and
113
+ `cancellable`. Types and generics describe the dynamic API; they do not validate
114
+ Python types at runtime.
115
+
116
+ **Calls are asynchronous; live access is synchronous.** Python functions, methods,
117
+ classes and builtins return Promises, including `await new cls(...)`.
118
+ Calls, imports, `exec` and `eval` execute in order on one native thread (a
119
+ node-ctypes `Executor`) without occupying a waiting libuv worker. Arguments and
120
+ results are converted on Node.js, so thousands of concurrent calls (e.g.
121
+ `Promise.all` over an array) hold Node.js while they are submitted and while
122
+ their results are converted: pass the data to one Python call instead, or host
123
+ Python in a worker (`examples/worker.ts`). Attributes, indices, assignment, enumeration, ordinary iteration, conversion and
124
+ disposal remain synchronous and can block Node.js. Native initialization and
125
+ finalization also run synchronously on the hosting Node.js thread.
126
+
127
+ Python coroutine results are automatically awaited through a separate asyncio
128
+ thread. Async iterators work in both directions. An async JavaScript callback
129
+ must be awaited from Python; a synchronous Python callback cannot return a
130
+ JavaScript Promise. `cancellable(fn)` adds an `AbortSignal` to callbacks that
131
+ cooperate with Python cancellation.
132
+
133
+ `python.run(operation, { signal })` accepts the Promise of a call, `exec`,
134
+ `eval` or `import`, or a Python awaitable, and rejects with `signal.reason`
135
+ on abort (`AbortSignal.timeout(ms)` for time limits). A queued operation is
136
+ skipped; running Python code receives one `KeyboardInterrupt`, so `finally`
137
+ blocks run and `except Exception` does not swallow it. On CPython 3.12 only,
138
+ a one-line loop that starts a `try` block (`try:` followed by `while True: ...`)
139
+ skips that `finally` when interrupted; put the loop body on its own line.
140
+ Native calls are
141
+ interrupted only when they return; asyncio work is cancelled. Synchronous proxy
142
+ access and JavaScript work cannot be aborted.
143
+
144
+ ### Values, memory and lifetime
145
+
146
+ - Scalars convert naturally; Python integers outside JavaScript's safe range
147
+ become bigints. Arrays, `Tuple`, objects/Maps and Sets copy to Python containers.
148
+ Dates become UTC datetimes; Temporal conversions require runtime support.
149
+ - Other Python objects remain live proxies. `eval()` and `proxy.toJS()` perform
150
+ deep conversion; ordinary call results use shallow conversion. Circular copies
151
+ are rejected; use live proxies or `byReference()` instead.
152
+ - Arbitrary JavaScript instances remain shared references. `byReference(value)`
153
+ also shares ordinary containers. Python attributes take precedence over dict keys.
154
+ - Buffer/Uint8Array values copy to Python bytes; other typed arrays, ArrayBuffers
155
+ and DataViews expose shared memoryviews. `byReference(buffer)` shares writable
156
+ memory. `proxy.toTypedArray()` requires a C-contiguous Python buffer and copies
157
+ read-only buffers. Do not detach, transfer or resize shared backing memory.
158
+ - Release owned proxies with `[Symbol.dispose]()` when practical, including
159
+ `PythonError.exception`. GC is nondeterministic. Disposal drops the reference
160
+ immediately; on free-threaded builds CPython may run the object's destructor
161
+ later, when the thread that created it next runs Python code. `PythonError` exposes `type`,
162
+ `traceback`, `exception` and, when available, the original JavaScript `cause`.
163
+
164
+ Only one JavaScript thread per process may host Python. A Node.js worker can
165
+ isolate synchronous access and conversions, but must finalize before terminating.
166
+ Wait for application work and Python threads before finalization; do not finalize
167
+ inside a Python callback. Repeated finalization is harmless; restart and
168
+ subinterpreters are not supported. Never use Python proxies or Python-backed
169
+ memory afterward.
170
+
171
+ Closing rejects new calls and drains accepted native operations, not every
172
+ pending coroutine: remaining awaits are rejected during teardown. Cleanup also
173
+ runs on normal `beforeExit`; `process.exit()` is not orderly finalization.
174
+ Shutdown can wait for Python threads and has no overall timeout.
175
+ Execute trusted Python code only.
176
+
177
+ ## Examples and tests
178
+
179
+ Run examples directly, for example `node examples/basics.ts`.
180
+ They cover usage in more detail than this overview:
181
+
182
+ | Example | Focus |
183
+ | --------------------------------------------- | --------------------------------------------- |
184
+ | [basics.ts](./examples/basics.ts) | Values, live objects, errors and conversions |
185
+ | [callbacks.ts](./examples/callbacks.ts) | JavaScript callbacks and constructors |
186
+ | [threads.ts](./examples/threads.ts) | Python threads and cross-thread callbacks |
187
+ | [async.ts](./examples/async.ts) | Await, cancellation and async iteration |
188
+ | [module.ts](./examples/module.ts) | JavaScript modules and local Python imports |
189
+ | [worker.ts](./examples/worker.ts) | Hosting Python in a Node.js worker |
190
+ | [cryptography.ts](./examples/cryptography.ts) | Python cryptography integration |
191
+ | [lxml.ts](./examples/lxml.ts) | XML parsing, XPath, XSLT and canonicalization |
192
+
193
+ Optional packages are needed only for the corresponding examples and must be
194
+ installed in the selected interpreter. Set `PYTHON` to that executable if it
195
+ differs from the one found automatically. The suite regression-tests callbacks
196
+ and missing-package diagnostics; other example scenarios are manual.
197
+
198
+ ```sh
199
+ npm run typecheck
200
+ npm test
201
+ npm run test:unit
202
+ npm run test:integration
203
+ npm run test:types
204
+ npm run test:backlog
205
+ npm run test:stress
206
+ ```
207
+
208
+ `npm test` builds and runs the ordinary suite; integration tests require shared
209
+ CPython. Typechecks include sources, examples and test helpers.
210
+ `test:backlog` checks queued ownership, every outcome and shutdown under load.
211
+ `test:stress` adds a 60-second mixed workload; set `NODE_PYTHON_STRESS_SECONDS`
212
+ to change its duration. Both are opt-in, force GC in isolated children and report
213
+ memory/latency diagnostics, not performance or leak-certification guarantees.
214
+ The runtime does not impose application backpressure.
215
+
216
+ Two manual checks run in Electron's main process after `npm run build`
217
+ (`electron <file>`, with `ELECTRON_RUN_AS_NODE` unset):
218
+ [tests/electron/main.mjs](./tests/electron/main.mjs) prints a JSON report of
219
+ calls, a free UI thread during a long call and bursts of calls;
220
+ [tests/electron/ui/main.mjs](./tests/electron/ui/main.mjs) opens a window that
221
+ charts frame times and main-process IPC latency while bursts run in the main
222
+ process or in the renderer (`--auto` runs both, prints the table and quits).
223
+
224
+ The [CI workflow](./.github/workflows/ci.yml) runs `npm test` with Python
225
+ 3.12, 3.13, 3.14, 3.14t and 3.15 on Windows, Linux and macOS. It is discovered only when
226
+ this package is a repository root, not while nested in another repository.
227
+ Pushing a `v<version>` tag that matches `package.json` publishes to npm once the
228
+ whole matrix passes (npm Trusted Publishing; versions with a `-` go to `next`).
229
+ For implementation diagrams and ownership invariants, see [FLOWS.md](./FLOWS.md)
230
+ (Italian).
@@ -5,10 +5,14 @@ export declare function nextCompletionToken(previous: number, pending: ReadonlyM
5
5
  export interface Cancellable {
6
6
  cancel?: () => void;
7
7
  }
8
- /** Python owns execution; completion notifications do not occupy libuv workers. */
8
+ /**
9
+ * Python requests run in order on a node-ctypes Executor thread (no libuv
10
+ * worker waits for them). Each request is a call of a Python ctypes callback
11
+ * on that thread; the thread keeps one Python thread state from start to close.
12
+ */
9
13
  export declare class PythonExecutor {
10
14
  #private;
11
- constructor(api: PythonLibrary, check: (ptr: Pointer) => bigint, withGIL: <T>(fn: () => T) => T, consume: (outcome: Pointer) => Pointer);
15
+ constructor(api: PythonLibrary, check: (ptr: Pointer) => bigint, withGIL: <T>(fn: () => T) => T);
12
16
  callAsync(request: Pointer, control?: Cancellable): Promise<Pointer>;
13
17
  close(): Promise<void>;
14
18
  abandon(): void;
package/dist/executor.js CHANGED
@@ -1,6 +1,5 @@
1
1
  // Copyright (c) 2026 Damiano Mazzella. MIT License (see LICENSE).
2
- import { setImmediate } from "node:timers/promises";
3
- import { c_int, threadSafeCallback } from "node-ctypes";
2
+ import { CFUNCTYPE, Executor, c_int, c_void_p } from "node-ctypes";
4
3
  import { Py_file_input } from "./native.js";
5
4
  export function nextCompletionToken(previous, pending) {
6
5
  if (pending.size >= 0x7fffffff)
@@ -11,158 +10,140 @@ export function nextCompletionToken(previous, pending) {
11
10
  } while (pending.has(token));
12
11
  return token;
13
12
  }
14
- const HELPERS = ["_enqueue", "_take", "_stop_request", "_alive", "_start", "_cancel"];
15
- const SOURCE = `
16
- import ctypes
17
- import importlib
18
- import queue
19
- import threading
20
-
21
- _queue = queue.SimpleQueue()
22
- _sentinel = object()
23
- _completed = {}
24
- _notify = ctypes.CFUNCTYPE(None, ctypes.c_int)(_notify_address)
25
- _base_error = BaseException
26
- _interrupt = KeyboardInterrupt
27
- _compile = compile
28
- _eval = eval
29
- _import = importlib.import_module
30
- _get_ident = threading.get_ident
31
- # Private prototypes: user code may configure ctypes.pythonapi differently.
32
- _async_exc = ctypes.cast(ctypes.pythonapi.PyThreadState_SetAsyncExc, ctypes.c_void_p).value
33
- _raise_async = ctypes.PYFUNCTYPE(ctypes.c_int, ctypes.c_ulong, ctypes.py_object)(_async_exc)
34
- _clear_async = ctypes.PYFUNCTYPE(ctypes.c_int, ctypes.c_ulong, ctypes.c_void_p)(_async_exc)
35
- # Reentrant only for _is_owned(): see _settle.
36
- _lock = threading.RLock()
37
- _ident = None
38
- _current = None
39
- _interrupted = False
40
- _waiting = set()
41
- _cancelled = set()
42
-
43
- def _execute(request):
44
- operation, *args = request
45
- if operation == "PyImport_ImportModule":
46
- return _import(args[0])
47
- if operation == "ExecuteSource":
48
- source, mode, namespace = args
49
- if mode not in (257, 258):
50
- raise ValueError(f"Unknown Python compilation mode: {mode}")
51
- return _eval(_compile(source, "<string>", "exec" if mode == 257 else "eval"), namespace, namespace)
52
- if operation == "PyObject_Call":
53
- function, positional, keywords = args
54
- return function(*positional) if keywords is None else function(*positional, **keywords)
55
- raise ValueError(f"Unknown Python execution operation: {operation}")
56
-
57
- def _run(request, token):
58
- global _current, _interrupted
59
- with _lock:
60
- _waiting.discard(token)
61
- if token in _cancelled:
62
- _cancelled.discard(token)
63
- raise _interrupt
64
- _current = token
65
- _interrupted = False
66
- try:
67
- return _execute(request)
68
- finally:
69
- _settle()
70
-
71
- def _settle():
72
- global _current
73
- while True:
74
- try:
75
- with _lock:
76
- _current = None
77
- _clear_async(_ident, None)
78
- return
79
- except _base_error:
80
- # An abort that landed after the operation completed. It can land
81
- # right after __enter__ acquired the lock, outside the with block's
82
- # protected range, so __exit__ never runs: release it here. At most
83
- # one abort is injected per operation, so none can land in here.
84
- if _lock._is_owned():
85
- _lock.release()
86
-
87
- def _cancel(token):
88
- # Inject at most once, and only into the operation that is running: a
89
- # late interrupt can leave _current stale, never pending for the next one.
90
- global _interrupted
91
- with _lock:
92
- if token == _current:
93
- if not _interrupted:
94
- _interrupted = True
95
- _raise_async(_ident, _interrupt)
96
- elif token in _waiting:
97
- _cancelled.add(token)
98
-
99
- def _enqueue(request, token):
100
- with _lock:
101
- _waiting.add(token)
102
- _queue.put((request, token))
103
-
104
- def _stop_request(token):
105
- _queue.put((_sentinel, token))
106
-
107
- def _take(token):
108
- return _completed.pop(token)
109
-
110
- def _alive():
111
- return _thread.is_alive()
112
-
113
- def _start():
114
- _thread.start()
115
-
116
- def _work():
117
- global _ident
118
- _ident = _get_ident()
119
- while True:
120
- request, token = _queue.get()
121
- stopping = request is _sentinel
122
- try:
123
- outcome = (True, None if stopping else _run(request, token))
124
- except _base_error as error:
125
- outcome = (False, error)
126
- _completed[token] = outcome
127
- del request, outcome
128
- _notify(token)
129
- del token
130
- if stopping:
131
- return
132
-
133
- _thread = threading.Thread(target=_work, name="node-python", daemon=True)
13
+ const HELPERS = ["_cancel", "_discard", "_cancelled_outcome"];
14
+ const SOURCE = `
15
+ import ctypes
16
+ import importlib
17
+ import threading
18
+
19
+ _base_error = BaseException
20
+ _interrupt = KeyboardInterrupt
21
+ _compile = compile
22
+ _eval = eval
23
+ _import = importlib.import_module
24
+ _get_ident = threading.get_ident
25
+ # Private prototypes: user code may configure ctypes.pythonapi differently.
26
+ _async_exc = ctypes.cast(ctypes.pythonapi.PyThreadState_SetAsyncExc, ctypes.c_void_p).value
27
+ _raise_async = ctypes.PYFUNCTYPE(ctypes.c_int, ctypes.c_ulong, ctypes.py_object)(_async_exc)
28
+ _clear_async = ctypes.PYFUNCTYPE(ctypes.c_int, ctypes.c_ulong, ctypes.c_void_p)(_async_exc)
29
+ _incref = ctypes.PYFUNCTYPE(None, ctypes.py_object)(ctypes.cast(ctypes.pythonapi.Py_IncRef, ctypes.c_void_p).value)
30
+ # Reentrant only for _is_owned(): see _settle.
31
+ _lock = threading.RLock()
32
+ _ident = None
33
+ _current = None
34
+ _interrupted = False
35
+ _cancelled = set()
36
+
37
+ def _execute(request):
38
+ operation, *args = request
39
+ if operation == "PyImport_ImportModule":
40
+ return _import(args[0])
41
+ if operation == "ExecuteSource":
42
+ source, mode, namespace = args
43
+ if mode not in (257, 258):
44
+ raise ValueError(f"Unknown Python compilation mode: {mode}")
45
+ return _eval(_compile(source, "<string>", "exec" if mode == 257 else "eval"), namespace, namespace)
46
+ if operation == "PyObject_Call":
47
+ function, positional, keywords = args
48
+ return function(*positional) if keywords is None else function(*positional, **keywords)
49
+ raise ValueError(f"Unknown Python execution operation: {operation}")
50
+
51
+ def _run(request, token):
52
+ global _current, _interrupted
53
+ with _lock:
54
+ if token in _cancelled:
55
+ _cancelled.discard(token)
56
+ raise _interrupt
57
+ _current = token
58
+ _interrupted = False
59
+ try:
60
+ return _execute(request)
61
+ finally:
62
+ _settle()
63
+
64
+ def _settle():
65
+ global _current
66
+ while True:
67
+ try:
68
+ with _lock:
69
+ _current = None
70
+ _clear_async(_ident, None)
71
+ return
72
+ except _base_error:
73
+ # An abort that landed after the operation completed. It can land
74
+ # right after __enter__ acquired the lock, outside the with block's
75
+ # protected range, so __exit__ never runs: release it here. At most
76
+ # one abort is injected per operation, so none can land in here.
77
+ if _lock._is_owned():
78
+ _lock.release()
79
+
80
+ def _cancel(token):
81
+ # Inject at most once, and only into the operation that is running. A
82
+ # request already taken by the executor thread but not started yet (it
83
+ # waits for the GIL) is marked: _run raises before executing it.
84
+ global _interrupted
85
+ with _lock:
86
+ if token == _current:
87
+ if not _interrupted:
88
+ _interrupted = True
89
+ _raise_async(_ident, _interrupt)
90
+ else:
91
+ _cancelled.add(token)
92
+
93
+ def _discard(token):
94
+ # A cancellation that arrived after its request completed.
95
+ with _lock:
96
+ _cancelled.discard(token)
97
+
98
+ def _cancelled_outcome():
99
+ return (False, _interrupt())
100
+
101
+ def _entry(request, token):
102
+ # Runs on the executor thread; ctypes takes the GIL around the callback.
103
+ # The outcome is returned as a new reference, owned by the host.
104
+ global _ident
105
+ _ident = _get_ident()
106
+ try:
107
+ outcome = (True, _run(request, token))
108
+ except _base_error as error:
109
+ outcome = (False, error)
110
+ _incref(outcome)
111
+ return id(outcome)
112
+
113
+ _entry_callback = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.py_object, ctypes.c_int)(_entry)
114
+ _entry_address = ctypes.cast(_entry_callback, ctypes.c_void_p).value
134
115
  `;
135
- /** Python owns execution; completion notifications do not occupy libuv workers. */
116
+ // Rejection reason of a request removed from the queue before it ran.
117
+ const CANCELLED = Symbol("cancelled");
118
+ /**
119
+ * Python requests run in order on a node-ctypes Executor thread (no libuv
120
+ * worker waits for them). Each request is a call of a Python ctypes callback
121
+ * on that thread; the thread keeps one Python thread state from start to close.
122
+ */
136
123
  export class PythonExecutor {
137
124
  #api;
138
125
  #namespace;
139
- #channel;
140
126
  #check;
141
127
  #withGIL;
142
- #consume;
143
128
  #helpers = new Map();
129
+ #executor;
130
+ #entry;
131
+ #restoreThread;
132
+ #releaseState;
133
+ #attached;
144
134
  #pending = new Map();
145
135
  #lastToken = 0;
146
136
  #closing;
147
137
  #abandoned = false;
148
- constructor(api, check, withGIL, consume) {
138
+ constructor(api, check, withGIL) {
149
139
  this.#api = api;
150
140
  this.#check = check;
151
141
  this.#withGIL = withGIL;
152
- this.#consume = consume;
142
+ let entry;
153
143
  try {
154
144
  this.#namespace = check(api.PyDict_New());
155
- this.#channel = threadSafeCallback((token) => this.#complete(token), null, [c_int]).unref();
156
145
  if (api.PyDict_SetItemString(this.#namespace, "__builtins__", api.PyEval_GetBuiltins()) < 0)
157
146
  check(null);
158
- const address = check(api.PyLong_FromLongLong(this.#channel.pointer));
159
- try {
160
- if (api.PyDict_SetItemString(this.#namespace, "_notify_address", address) < 0)
161
- check(null);
162
- }
163
- finally {
164
- api.Py_DecRef(address);
165
- }
166
147
  const code = check(api.Py_CompileString(SOURCE, "<node-python executor>", Py_file_input));
167
148
  try {
168
149
  api.Py_DecRef(check(api.PyEval_EvalCode(code, this.#namespace, this.#namespace)));
@@ -175,26 +156,75 @@ export class PythonExecutor {
175
156
  api.Py_IncRef(helper);
176
157
  this.#helpers.set(name, helper);
177
158
  }
178
- api.Py_DecRef(this.#call("_start"));
159
+ entry = BigInt(api.PyLong_AsLongLong(check(api.PyDict_GetItemString(this.#namespace, "_entry_address"))));
179
160
  }
180
161
  catch (error) {
181
162
  this.#releasePython();
182
- this.#channel?.release();
183
163
  throw error;
184
164
  }
165
+ // Started only once the Python side is complete: a failed setup leaves no
166
+ // thread holding a thread state. Own bindings: the host's wrappers count
167
+ // as host acquisitions (and tests replace them).
168
+ this.#executor = new Executor({ name: "node-python" });
169
+ this.#entry = CFUNCTYPE(c_void_p, c_void_p, c_int)(entry);
170
+ this.#restoreThread = api.func("PyEval_RestoreThread", null, [c_void_p]);
171
+ this.#releaseState = api.func("PyGILState_Release", null, [c_int]);
172
+ // The first jobs give the executor thread a thread state and release the
173
+ // GIL: thread-local Python state survives between requests.
174
+ const ensure = api.func("PyGILState_Ensure", c_int, []).callOn(this.#executor);
175
+ const save = api.func("PyEval_SaveThread", c_void_p, []).callOn(this.#executor);
176
+ this.#attached = Promise.all([ensure, save]);
177
+ this.#attached.catch(() => undefined);
185
178
  }
186
179
  callAsync(request, control) {
187
180
  if (this.#abandoned || this.#closing)
188
181
  return Promise.reject(new Error("Python executor is closing"));
189
- return this.#dispatch(request, false, control);
182
+ let token;
183
+ try {
184
+ token = nextCompletionToken(this.#lastToken, this.#pending);
185
+ }
186
+ catch (error) {
187
+ return Promise.reject(error);
188
+ }
189
+ this.#lastToken = token;
190
+ // Submitted without the GIL held by the host: the executor thread takes it
191
+ // at once, and a short request completes while the host waits inline.
192
+ const call = { executor: this.#executor, _job: 0 };
193
+ const task = this.#entry.callOn(call, request, token);
194
+ const job = call._job;
195
+ let cancelled = false;
196
+ if (control)
197
+ control.cancel = () => {
198
+ if (cancelled || this.#abandoned)
199
+ return;
200
+ cancelled = true;
201
+ // Still queued: removed without running. Otherwise Python interrupts it.
202
+ if (!this.#executor._cancel(job, CANCELLED))
203
+ this.#tokenHelper("_cancel", token);
204
+ };
205
+ const settled = task
206
+ .then((outcome) => {
207
+ if (cancelled)
208
+ this.#tokenHelper("_discard", token);
209
+ return outcome;
210
+ }, (error) => {
211
+ if (error === CANCELLED)
212
+ return this.#withGIL(() => this.#call("_cancelled_outcome"));
213
+ throw error;
214
+ })
215
+ .finally(() => {
216
+ if (control)
217
+ control.cancel = undefined;
218
+ this.#pending.delete(token);
219
+ });
220
+ this.#pending.set(token, settled);
221
+ return settled;
190
222
  }
191
- #cancel(token) {
192
- if (this.#abandoned || !this.#pending.has(token))
193
- return;
223
+ #tokenHelper(name, token) {
194
224
  this.#withGIL(() => {
195
225
  const id = this.#check(this.#api.PyLong_FromLongLong(token));
196
226
  try {
197
- this.#api.Py_DecRef(this.#call("_cancel", [id]));
227
+ this.#api.Py_DecRef(this.#call(name, [id]));
198
228
  }
199
229
  finally {
200
230
  this.#api.Py_DecRef(id);
@@ -225,107 +255,30 @@ export class PythonExecutor {
225
255
  if (this.#namespace)
226
256
  this.#api.Py_DecRef(this.#namespace);
227
257
  }
228
- #dispatch(request, stopping = false, control) {
229
- let token;
230
- try {
231
- token = nextCompletionToken(this.#lastToken, this.#pending);
232
- }
233
- catch (error) {
234
- return Promise.reject(error);
235
- }
236
- this.#lastToken = token;
237
- let resolve;
238
- let reject;
239
- const promise = new Promise((ok, fail) => {
240
- resolve = ok;
241
- reject = fail;
242
- });
243
- this.#pending.set(token, { promise, resolve, reject, control });
244
- if (this.#pending.size === 1)
245
- this.#channel.ref();
246
- try {
247
- this.#withGIL(() => {
248
- const id = this.#check(this.#api.PyLong_FromLongLong(token));
249
- try {
250
- this.#api.Py_DecRef(this.#call(stopping ? "_stop_request" : "_enqueue", stopping ? [id] : [request, id]));
251
- }
252
- finally {
253
- this.#api.Py_DecRef(id);
254
- }
255
- });
256
- if (control)
257
- control.cancel = () => this.#cancel(token);
258
- }
259
- catch (error) {
260
- this.#pending.delete(token);
261
- if (this.#pending.size === 0)
262
- this.#channel.unref();
263
- reject(error);
264
- }
265
- return promise;
266
- }
267
- #complete(token) {
268
- if (this.#abandoned)
269
- return;
270
- const pending = this.#pending.get(token);
271
- if (!pending)
272
- throw new Error(`Unknown Python executor completion: ${token}`);
273
- this.#pending.delete(token);
274
- if (pending.control)
275
- pending.control.cancel = undefined;
276
- try {
277
- const outcome = this.#withGIL(() => {
278
- const id = this.#check(this.#api.PyLong_FromLongLong(token));
279
- try {
280
- return this.#call("_take", [id]);
281
- }
282
- finally {
283
- this.#api.Py_DecRef(id);
284
- }
285
- });
286
- pending.resolve(outcome);
287
- }
288
- catch (error) {
289
- pending.reject(error);
290
- }
291
- finally {
292
- if (this.#pending.size === 0)
293
- this.#channel.unref();
294
- }
295
- }
296
258
  close() {
297
259
  this.#closing ??= this.#finish();
298
260
  return this.#closing;
299
261
  }
300
262
  async #finish() {
301
- await Promise.allSettled([...this.#pending.values()].map(({ promise }) => promise));
302
- const outcome = await this.#dispatch(null, true);
263
+ await Promise.allSettled([...this.#pending.values()]);
303
264
  try {
304
- this.#withGIL(() => this.#api.Py_DecRef(this.#consume(outcome)));
265
+ const [state, threadState] = await this.#attached;
266
+ // FIFO, after every accepted request: the thread state is released on
267
+ // its own thread, then the thread stops. Both are queued before waiting:
268
+ // between them the executor thread holds the GIL, and it must not wait
269
+ // for this thread, which may take the GIL meanwhile (e.g. stats()).
270
+ const restored = this.#restoreThread.callOn(this.#executor, threadState);
271
+ const released = this.#releaseState.callOn(this.#executor, state);
272
+ await Promise.all([restored, released]);
305
273
  }
306
274
  finally {
307
- // A completion can arrive before its native callback returns on Python.
308
- while (this.#withGIL(() => {
309
- const alive = this.#call("_alive");
310
- try {
311
- const result = this.#api.PyObject_IsTrue(alive);
312
- if (result < 0)
313
- this.#check(null);
314
- return result !== 0;
315
- }
316
- finally {
317
- this.#api.Py_DecRef(alive);
318
- }
319
- })) {
320
- await setImmediate();
321
- }
275
+ await this.#executor.close();
322
276
  this.#withGIL(() => this.#releasePython());
323
- this.#channel.release();
324
277
  }
325
278
  }
326
279
  abandon() {
327
- // Forced exit retains Python/callback owners until the OS tears down the process.
280
+ // Forced exit retains Python owners until the OS tears down the process;
281
+ // node-ctypes leaves the executor thread to the process exit.
328
282
  this.#abandoned = true;
329
- this.#channel.unref();
330
283
  }
331
284
  }
@@ -2,5 +2,14 @@ import type { InternalPythonObject as PythonObject } from "./types.ts";
2
2
  export declare class PythonPlatform {
3
3
  #private;
4
4
  constructor(builtins: PythonObject, importModule: (name: string) => PythonObject, module: PythonObject);
5
- redirect(name: "stdout" | "stderr", write: (text: string) => void): void;
5
+ redirect(name: "stdout" | "stderr", write: (text: string) => void, flush?: () => void): void;
6
6
  }
7
+ /**
8
+ * Whole lines for `emit` (e.g. console.log) from text written in pieces:
9
+ * `print("a", "b")` writes "a", " ", "b", "\n". A line without its newline
10
+ * is emitted by `flush` (Python's flush(), and the flush at finalization).
11
+ */
12
+ export declare function lineWriter(emit: (line: string) => void): {
13
+ write: (text: string) => void;
14
+ flush: () => void;
15
+ };
package/dist/platform.js CHANGED
@@ -5,9 +5,11 @@ const PLATFORM_ADAPTERS = `
5
5
  class JsStream(io.TextIOBase):
6
6
  encoding = "utf-8"
7
7
  errors = "strict"
8
- def __init__(self, name, write):
9
- self.name, self._write = name, write
8
+ def __init__(self, name, write, flush=None):
9
+ self.name, self._write, self._flush = name, write, flush
10
10
  def writable(self): return True
11
+ def flush(self):
12
+ if self._flush is not None: self._flush()
11
13
  def write(self, text):
12
14
  if not isinstance(text, str):
13
15
  raise TypeError(f"write() argument must be str, not {type(text).__name__}")
@@ -24,6 +26,9 @@ export class PythonPlatform {
24
26
  module.io = importModule("io");
25
27
  definePython(builtins, module, PLATFORM_ADAPTERS, "<node-python stream and timer adapters>");
26
28
  for (const stream of [this.#sys.stdout, this.#sys.stderr]) {
29
+ // None without a console (an Electron renderer, a packaged GUI app on Windows).
30
+ if (stream === null)
31
+ continue;
27
32
  try {
28
33
  stream.reconfigure(kwargs({ encoding: "utf-8", line_buffering: true }));
29
34
  }
@@ -34,7 +39,30 @@ export class PythonPlatform {
34
39
  }
35
40
  }
36
41
  }
37
- redirect(name, write) {
38
- this.#sys[name] = this.#module.JsStream(`<node ${name}>`, write);
42
+ redirect(name, write, flush) {
43
+ this.#sys[name] = this.#module.JsStream(`<node ${name}>`, write, flush ?? null);
39
44
  }
40
45
  }
46
+ /**
47
+ * Whole lines for `emit` (e.g. console.log) from text written in pieces:
48
+ * `print("a", "b")` writes "a", " ", "b", "\n". A line without its newline
49
+ * is emitted by `flush` (Python's flush(), and the flush at finalization).
50
+ */
51
+ export function lineWriter(emit) {
52
+ let pending = "";
53
+ return {
54
+ write(text) {
55
+ const lines = (pending + text).split("\n");
56
+ pending = lines.pop();
57
+ for (const line of lines)
58
+ emit(line);
59
+ },
60
+ flush() {
61
+ if (!pending)
62
+ return;
63
+ const line = pending;
64
+ pending = "";
65
+ emit(line);
66
+ },
67
+ };
68
+ }
package/dist/runtime.d.ts CHANGED
@@ -15,8 +15,8 @@ export declare class Python {
15
15
  * @param {string} [options.executable] - Python interpreter whose library and environment are used (default: $PYTHON, python3, python, py)
16
16
  * @param {string} [options.library] - Explicit path of the Python shared library (default: $PYTHON_LIBRARY); same version as the interpreter
17
17
  * @param {boolean} [options.stdin=true] - false: Python does not read the process stdin (sys.stdin is None), left to Node.js
18
- * @param {"inherit"|"node"|Function} [options.stdout="inherit"] - sys.stdout: the process stdout ("inherit"), process.stdout of Node.js, in order with console.log ("node"), or a function receiving the text
19
- * @param {"inherit"|"node"|Function} [options.stderr="inherit"] - sys.stderr, as stdout
18
+ * @param {"inherit"|"node"|"console"|Function} [options.stdout="inherit"] - sys.stdout: the process stdout ("inherit"), process.stdout of Node.js, in order with console.log ("node"), whole lines to console.log ("console", e.g. DevTools in an Electron renderer), or a function receiving the text
19
+ * @param {"inherit"|"node"|"console"|Function} [options.stderr="inherit"] - sys.stderr, as stdout ("console": console.error)
20
20
  * @param {boolean} [options.synchronousCallbacks=false] - serve native callbacks during interruptible synchronous Python waits
21
21
  * @param {number} [options.switchInterval=5] - GIL switch interval in milliseconds (sys.setswitchinterval), as in CPython; a smaller value (0.5) keeps the Node.js event loop responsive while Python threads run CPU-bound code, at the cost of slower contended Python threads
22
22
  * @returns {Promise<Python>}
package/dist/runtime.js CHANGED
@@ -4,7 +4,7 @@ import { addressof, byref, memmove, array, EXTERNAL_BUFFERS, c_char_p, c_void_p,
4
4
  import { API, MIN_PYTHON, Py_file_input, Py_eval_input, METH_VARARGS, METH_KEYWORDS, PyMethodDef, TYPES } from "./native.js";
5
5
  import { PythonBootstrap } from "./bootstrap.js";
6
6
  import { PythonScheduler } from "./scheduler.js";
7
- import { PythonPlatform } from "./platform.js";
7
+ import { PythonPlatform, lineWriter } from "./platform.js";
8
8
  import { PythonConversions } from "./conversions.js";
9
9
  import { PythonBuffers } from "./buffers.js";
10
10
  import { PythonExecutor } from "./executor.js";
@@ -24,6 +24,11 @@ class ProxyStates extends WeakMap {
24
24
  }
25
25
  }
26
26
  const DONE = Symbol("done");
27
+ // SharedArrayBuffer is not defined where the page is not cross-origin isolated
28
+ // (e.g. an Electron renderer): only an ArrayBuffer can be passed there.
29
+ function isArrayBuffer(value) {
30
+ return value instanceof ArrayBuffer || (typeof SharedArrayBuffer === "function" && value instanceof SharedArrayBuffer);
31
+ }
27
32
  function isThenable(value) {
28
33
  return value !== null && (typeof value === "object" || typeof value === "function") && typeof Reflect.get(value, "then") === "function";
29
34
  }
@@ -126,8 +131,8 @@ export class Python {
126
131
  * @param {string} [options.executable] - Python interpreter whose library and environment are used (default: $PYTHON, python3, python, py)
127
132
  * @param {string} [options.library] - Explicit path of the Python shared library (default: $PYTHON_LIBRARY); same version as the interpreter
128
133
  * @param {boolean} [options.stdin=true] - false: Python does not read the process stdin (sys.stdin is None), left to Node.js
129
- * @param {"inherit"|"node"|Function} [options.stdout="inherit"] - sys.stdout: the process stdout ("inherit"), process.stdout of Node.js, in order with console.log ("node"), or a function receiving the text
130
- * @param {"inherit"|"node"|Function} [options.stderr="inherit"] - sys.stderr, as stdout
134
+ * @param {"inherit"|"node"|"console"|Function} [options.stdout="inherit"] - sys.stdout: the process stdout ("inherit"), process.stdout of Node.js, in order with console.log ("node"), whole lines to console.log ("console", e.g. DevTools in an Electron renderer), or a function receiving the text
135
+ * @param {"inherit"|"node"|"console"|Function} [options.stderr="inherit"] - sys.stderr, as stdout ("console": console.error)
131
136
  * @param {boolean} [options.synchronousCallbacks=false] - serve native callbacks during interruptible synchronous Python waits
132
137
  * @param {number} [options.switchInterval=5] - GIL switch interval in milliseconds (sys.setswitchinterval), as in CPython; a smaller value (0.5) keeps the Node.js event loop responsive while Python threads run CPU-bound code, at the cost of slower contended Python threads
133
138
  * @returns {Promise<Python>}
@@ -172,8 +177,8 @@ export class Python {
172
177
  throw new TypeError("options.nativeObjects has been removed: native objects are always enabled; use options.synchronousCallbacks for interruptible synchronous waits");
173
178
  const { executable, library = process.env.PYTHON_LIBRARY, stdin = true, stdout = "inherit", stderr = "inherit", synchronousCallbacks = false, switchInterval = 5 } = options;
174
179
  for (const [name, value] of Object.entries({ stdout, stderr })) {
175
- if (value !== "inherit" && value !== "node" && typeof value !== "function")
176
- throw new TypeError(`options.${name} must be "inherit", "node" or a function`);
180
+ if (value !== "inherit" && value !== "node" && value !== "console" && typeof value !== "function")
181
+ throw new TypeError(`options.${name} must be "inherit", "node", "console" or a function`);
177
182
  }
178
183
  if (typeof synchronousCallbacks !== "boolean")
179
184
  throw new TypeError("options.synchronousCallbacks must be a boolean");
@@ -268,7 +273,7 @@ export class Python {
268
273
  if (setHome)
269
274
  delete process.env.PYTHONHOME;
270
275
  }
271
- this.#executor = this.#withGIL(() => new PythonExecutor(this.#api, (ptr) => this.#check(ptr), (fn) => this.#withGIL(fn, true), (outcome) => this.#consumeOutcome(outcome)));
276
+ this.#executor = this.#withGIL(() => new PythonExecutor(this.#api, (ptr) => this.#check(ptr), (fn) => this.#withGIL(fn, true)));
272
277
  for (const name of [
273
278
  "threading",
274
279
  "types",
@@ -382,6 +387,11 @@ export class Python {
382
387
  const target = streams[name];
383
388
  if (target === "inherit")
384
389
  continue;
390
+ if (target === "console") {
391
+ const lines = lineWriter(name === "stdout" ? (line) => console.log(line) : (line) => console.error(line));
392
+ this.#platform.redirect(name, lines.write, lines.flush);
393
+ continue;
394
+ }
385
395
  const write = target === "node" ? (text) => void process[name].write(text) : (text) => void target(text);
386
396
  this.#platform.redirect(name, write);
387
397
  }
@@ -761,28 +771,27 @@ export class Python {
761
771
  }
762
772
  }
763
773
  async #nativeCall(name, args, control) {
764
- const { request, task } = this.#withGIL(() => {
765
- const request = this.#filled(this.#api.PyTuple_New(args.length + 1), (tuple) => {
766
- this.#status(this.#api.PyTuple_SetItem(tuple, 0, this.#toPy(name)));
767
- args.forEach((value, i) => {
768
- const pointerArgument = name === "ExecuteSource" ? i === 2 : API[name][1][i] === c_void_p;
769
- const ptr = pointerArgument && value !== null ? this.#check(typeof value === "bigint" ? value : null) : this.#toPy(value);
770
- if (pointerArgument && value !== null)
771
- this.#api.Py_IncRef(ptr);
772
- this.#status(this.#api.PyTuple_SetItem(tuple, i + 1, ptr));
773
- });
774
+ const request = this.#withGIL(() => this.#filled(this.#api.PyTuple_New(args.length + 1), (tuple) => {
775
+ this.#status(this.#api.PyTuple_SetItem(tuple, 0, this.#toPy(name)));
776
+ args.forEach((value, i) => {
777
+ const pointerArgument = name === "ExecuteSource" ? i === 2 : API[name][1][i] === c_void_p;
778
+ const ptr = pointerArgument && value !== null ? this.#check(typeof value === "bigint" ? value : null) : this.#toPy(value);
779
+ if (pointerArgument && value !== null)
780
+ this.#api.Py_IncRef(ptr);
781
+ this.#status(this.#api.PyTuple_SetItem(tuple, i + 1, ptr));
774
782
  });
775
- try {
776
- const task = this.#executor.callAsync(request, control);
777
- if (control?.aborted)
778
- control.cancel?.();
779
- return { request, task };
780
- }
781
- catch (error) {
782
- this.#api.Py_DecRef(request);
783
- throw error;
784
- }
785
- }, true);
783
+ }), true);
784
+ // Submitted after releasing the GIL: the executor thread can take it at once.
785
+ let task;
786
+ try {
787
+ task = this.#executor.callAsync(request, control);
788
+ if (control?.aborted)
789
+ control.cancel?.();
790
+ }
791
+ catch (error) {
792
+ this.#withGIL(() => this.#api.Py_DecRef(request), true);
793
+ throw error;
794
+ }
786
795
  try {
787
796
  const outcome = await task;
788
797
  return this.#withGIL(() => this.#consumeOutcome(outcome), true);
@@ -1071,7 +1080,7 @@ export class Python {
1071
1080
  }
1072
1081
  if (value instanceof Uint8Array && !(value instanceof Uint8ClampedArray))
1073
1082
  return this.#check(api.PyBytes_FromStringAndSize(Buffer.from(value.buffer, value.byteOffset, value.byteLength), value.byteLength));
1074
- if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof SharedArrayBuffer)
1083
+ if (ArrayBuffer.isView(value) || isArrayBuffer(value))
1075
1084
  return this.#memoryview(value);
1076
1085
  if (typeof value !== "object")
1077
1086
  throw new TypeError(`Cannot convert a JavaScript ${typeof value} to Python`);
@@ -1113,7 +1122,7 @@ export class Python {
1113
1122
  }
1114
1123
  /** byReference(value) → new reference. */
1115
1124
  #reference(value) {
1116
- if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof SharedArrayBuffer)
1125
+ if (ArrayBuffer.isView(value) || isArrayBuffer(value))
1117
1126
  return this.#memoryview(value);
1118
1127
  if (value === null || typeof value !== "object" || this.#states.has(value))
1119
1128
  return this.#toPy(value);
@@ -1149,7 +1158,7 @@ export class Python {
1149
1158
  }
1150
1159
  /** memoryview sharing the memory of a typed array / ArrayBuffer / DataView (new reference). */
1151
1160
  #memoryview(value) {
1152
- const view = value instanceof ArrayBuffer || value instanceof SharedArrayBuffer ? new Uint8Array(value) : value;
1161
+ const view = isArrayBuffer(value) ? new Uint8Array(value) : value;
1153
1162
  const bytes = Buffer.from(view.buffer, view.byteOffset, view.byteLength);
1154
1163
  const format = FORMATS[view.constructor.name] ?? "B"; // DataView: bytes
1155
1164
  const address = bytes.length ? addressof(bytes) : 0n;
package/dist/types.d.ts CHANGED
@@ -25,7 +25,7 @@ type Float16ArrayIfAvailable = typeof globalThis extends {
25
25
  Float16Array: abstract new (...args: never) => infer T;
26
26
  } ? T : never;
27
27
  export type PythonTypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float16ArrayIfAvailable | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
28
- export type OutputTarget = "inherit" | "node" | ((text: string) => unknown);
28
+ export type OutputTarget = "inherit" | "node" | "console" | ((text: string) => unknown);
29
29
  export interface StreamOptions {
30
30
  stdin: boolean;
31
31
  stdout: OutputTarget;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@node-ctypes/python",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Typed embedded CPython for Node.js, powered by node-ctypes",
5
5
  "author": "Damiano Mazzella",
6
6
  "license": "MIT",
@@ -54,7 +54,7 @@
54
54
  "prepublishOnly": "npm test"
55
55
  },
56
56
  "dependencies": {
57
- "node-ctypes": "^2.10.0"
57
+ "node-ctypes": "^2.12.2"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/node": "^26.6.6",