@node-ctypes/python 0.1.1 → 0.2.1
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 +230 -214
- package/dist/executor.d.ts +13 -3
- package/dist/executor.js +213 -236
- package/dist/platform.d.ts +10 -1
- package/dist/platform.js +32 -4
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.js +110 -72
- package/dist/types.d.ts +1 -1
- package/package.json +2 -2
package/dist/executor.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// Copyright (c) 2026 Damiano Mazzella. MIT License (see LICENSE).
|
|
2
|
-
import {
|
|
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,150 @@ export function nextCompletionToken(previous, pending) {
|
|
|
11
10
|
} while (pending.has(token));
|
|
12
11
|
return token;
|
|
13
12
|
}
|
|
14
|
-
const HELPERS = ["
|
|
15
|
-
const SOURCE = `
|
|
16
|
-
import ctypes
|
|
17
|
-
import importlib
|
|
18
|
-
import
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
#
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
operation
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
source, mode, namespace
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
return
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
#
|
|
81
|
-
#
|
|
82
|
-
#
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
#
|
|
89
|
-
#
|
|
90
|
-
global _interrupted
|
|
91
|
-
with _lock:
|
|
92
|
-
if token == _current:
|
|
93
|
-
if not _interrupted:
|
|
94
|
-
_interrupted = True
|
|
95
|
-
_raise_async(_ident, _interrupt)
|
|
96
|
-
|
|
97
|
-
_cancelled.add(token)
|
|
98
|
-
|
|
99
|
-
def
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
def
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
def
|
|
108
|
-
return
|
|
109
|
-
|
|
110
|
-
def
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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", "_take_failure", "_cancelled_failure"];
|
|
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
|
+
# Exceptions of failed requests, by token, until the host takes them.
|
|
37
|
+
_failures = {}
|
|
38
|
+
|
|
39
|
+
def _execute(request):
|
|
40
|
+
operation, *args = request
|
|
41
|
+
if operation == "PyImport_ImportModule":
|
|
42
|
+
return _import(args[0])
|
|
43
|
+
if operation == "ExecuteSource":
|
|
44
|
+
source, mode, namespace = args
|
|
45
|
+
if mode not in (257, 258):
|
|
46
|
+
raise ValueError(f"Unknown Python compilation mode: {mode}")
|
|
47
|
+
return _eval(_compile(source, "<string>", "exec" if mode == 257 else "eval"), namespace, namespace)
|
|
48
|
+
if operation == "PyObject_Call":
|
|
49
|
+
function, positional, keywords = args
|
|
50
|
+
return function(*positional) if keywords is None else function(*positional, **keywords)
|
|
51
|
+
raise ValueError(f"Unknown Python execution operation: {operation}")
|
|
52
|
+
|
|
53
|
+
def _run(request, token):
|
|
54
|
+
global _current, _interrupted
|
|
55
|
+
with _lock:
|
|
56
|
+
if token in _cancelled:
|
|
57
|
+
_cancelled.discard(token)
|
|
58
|
+
raise _interrupt
|
|
59
|
+
_current = token
|
|
60
|
+
_interrupted = False
|
|
61
|
+
try:
|
|
62
|
+
return _execute(request)
|
|
63
|
+
finally:
|
|
64
|
+
_settle()
|
|
65
|
+
|
|
66
|
+
def _settle():
|
|
67
|
+
global _current
|
|
68
|
+
while True:
|
|
69
|
+
try:
|
|
70
|
+
with _lock:
|
|
71
|
+
_current = None
|
|
72
|
+
# Only an injected abort can be pending: _cancel injects under
|
|
73
|
+
# this lock, while this request is _current.
|
|
74
|
+
if _interrupted:
|
|
75
|
+
_clear_async(_ident, None)
|
|
76
|
+
return
|
|
77
|
+
except _base_error:
|
|
78
|
+
# An abort that landed after the operation completed. It can land
|
|
79
|
+
# right after __enter__ acquired the lock, outside the with block's
|
|
80
|
+
# protected range, so __exit__ never runs: release it here. At most
|
|
81
|
+
# one abort is injected per operation, so none can land in here.
|
|
82
|
+
if _lock._is_owned():
|
|
83
|
+
_lock.release()
|
|
84
|
+
|
|
85
|
+
def _cancel(token):
|
|
86
|
+
# Inject at most once, and only into the operation that is running. A
|
|
87
|
+
# request already taken by the executor thread but not started yet (it
|
|
88
|
+
# waits for the GIL) is marked: _run raises before executing it.
|
|
89
|
+
global _interrupted
|
|
90
|
+
with _lock:
|
|
91
|
+
if token == _current:
|
|
92
|
+
if not _interrupted:
|
|
93
|
+
_interrupted = True
|
|
94
|
+
_raise_async(_ident, _interrupt)
|
|
95
|
+
else:
|
|
96
|
+
_cancelled.add(token)
|
|
97
|
+
|
|
98
|
+
def _discard(token):
|
|
99
|
+
# A cancellation that arrived after its request completed.
|
|
100
|
+
with _lock:
|
|
101
|
+
_cancelled.discard(token)
|
|
102
|
+
|
|
103
|
+
def _take_failure(token):
|
|
104
|
+
return _failures.pop(token)
|
|
105
|
+
|
|
106
|
+
def _cancelled_failure():
|
|
107
|
+
return _interrupt()
|
|
108
|
+
|
|
109
|
+
def _entry(request, token):
|
|
110
|
+
# Runs on the executor thread; ctypes takes the GIL around the callback.
|
|
111
|
+
# The value is returned as a new reference, owned by the host; a failure
|
|
112
|
+
# returns NULL and keeps its exception for _take_failure.
|
|
113
|
+
global _ident
|
|
114
|
+
_ident = _get_ident()
|
|
115
|
+
try:
|
|
116
|
+
value = _run(request, token)
|
|
117
|
+
except _base_error as error:
|
|
118
|
+
_failures[token] = error
|
|
119
|
+
return None
|
|
120
|
+
_incref(value)
|
|
121
|
+
return id(value)
|
|
122
|
+
|
|
123
|
+
_entry_callback = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.py_object, ctypes.c_int)(_entry)
|
|
124
|
+
_entry_address = ctypes.cast(_entry_callback, ctypes.c_void_p).value
|
|
134
125
|
`;
|
|
135
|
-
|
|
126
|
+
// Rejection reason of a request removed from the queue before it ran.
|
|
127
|
+
const CANCELLED = Symbol("cancelled");
|
|
128
|
+
/**
|
|
129
|
+
* Python requests run in order on a node-ctypes Executor thread (no libuv
|
|
130
|
+
* worker waits for them). Each request is a call of a Python ctypes callback
|
|
131
|
+
* on that thread; the thread keeps one Python thread state from start to close.
|
|
132
|
+
*/
|
|
136
133
|
export class PythonExecutor {
|
|
137
134
|
#api;
|
|
138
135
|
#namespace;
|
|
139
|
-
#channel;
|
|
140
136
|
#check;
|
|
141
137
|
#withGIL;
|
|
142
|
-
#consume;
|
|
143
138
|
#helpers = new Map();
|
|
139
|
+
#executor;
|
|
140
|
+
#entry;
|
|
141
|
+
#restoreThread;
|
|
142
|
+
#releaseState;
|
|
143
|
+
#attached;
|
|
144
144
|
#pending = new Map();
|
|
145
145
|
#lastToken = 0;
|
|
146
146
|
#closing;
|
|
147
147
|
#abandoned = false;
|
|
148
|
-
constructor(api, check, withGIL
|
|
148
|
+
constructor(api, check, withGIL) {
|
|
149
149
|
this.#api = api;
|
|
150
150
|
this.#check = check;
|
|
151
151
|
this.#withGIL = withGIL;
|
|
152
|
-
|
|
152
|
+
let entry;
|
|
153
153
|
try {
|
|
154
154
|
this.#namespace = check(api.PyDict_New());
|
|
155
|
-
this.#channel = threadSafeCallback((token) => this.#complete(token), null, [c_int]).unref();
|
|
156
155
|
if (api.PyDict_SetItemString(this.#namespace, "__builtins__", api.PyEval_GetBuiltins()) < 0)
|
|
157
156
|
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
157
|
const code = check(api.Py_CompileString(SOURCE, "<node-python executor>", Py_file_input));
|
|
167
158
|
try {
|
|
168
159
|
api.Py_DecRef(check(api.PyEval_EvalCode(code, this.#namespace, this.#namespace)));
|
|
@@ -175,31 +166,94 @@ export class PythonExecutor {
|
|
|
175
166
|
api.Py_IncRef(helper);
|
|
176
167
|
this.#helpers.set(name, helper);
|
|
177
168
|
}
|
|
178
|
-
api.
|
|
169
|
+
entry = BigInt(api.PyLong_AsLongLong(check(api.PyDict_GetItemString(this.#namespace, "_entry_address"))));
|
|
179
170
|
}
|
|
180
171
|
catch (error) {
|
|
181
172
|
this.#releasePython();
|
|
182
|
-
this.#channel?.release();
|
|
183
173
|
throw error;
|
|
184
174
|
}
|
|
175
|
+
// Started only once the Python side is complete: a failed setup leaves no
|
|
176
|
+
// thread holding a thread state. Own bindings: the host's wrappers count
|
|
177
|
+
// as host acquisitions (and tests replace them).
|
|
178
|
+
this.#executor = new Executor({ name: "node-python" });
|
|
179
|
+
this.#entry = CFUNCTYPE(c_void_p, c_void_p, c_int)(entry);
|
|
180
|
+
this.#restoreThread = api.func("PyEval_RestoreThread", null, [c_void_p]);
|
|
181
|
+
this.#releaseState = api.func("PyGILState_Release", null, [c_int]);
|
|
182
|
+
// The first jobs give the executor thread a thread state and release the
|
|
183
|
+
// GIL: thread-local Python state survives between requests.
|
|
184
|
+
const ensure = api.func("PyGILState_Ensure", c_int, []).callOn(this.#executor);
|
|
185
|
+
const save = api.func("PyEval_SaveThread", c_void_p, []).callOn(this.#executor);
|
|
186
|
+
this.#attached = Promise.all([ensure, save]);
|
|
187
|
+
this.#attached.catch(() => undefined);
|
|
185
188
|
}
|
|
186
189
|
callAsync(request, control) {
|
|
187
190
|
if (this.#abandoned || this.#closing)
|
|
188
191
|
return Promise.reject(new Error("Python executor is closing"));
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
192
|
+
let token;
|
|
193
|
+
try {
|
|
194
|
+
token = nextCompletionToken(this.#lastToken, this.#pending);
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
return Promise.reject(error);
|
|
198
|
+
}
|
|
199
|
+
this.#lastToken = token;
|
|
200
|
+
// Submitted without the GIL held by the host: the executor thread takes it
|
|
201
|
+
// at once, and a short request completes while the host waits inline.
|
|
202
|
+
const call = { executor: this.#executor, _job: 0 };
|
|
203
|
+
const task = this.#entry.callOn(call, request, token);
|
|
204
|
+
const job = call._job;
|
|
205
|
+
let cancelled = false;
|
|
206
|
+
if (control)
|
|
207
|
+
control.cancel = () => {
|
|
208
|
+
if (cancelled || this.#abandoned)
|
|
209
|
+
return;
|
|
210
|
+
cancelled = true;
|
|
211
|
+
// Still queued: removed without running. Otherwise Python interrupts it.
|
|
212
|
+
if (!this.#executor._cancel(job, CANCELLED))
|
|
213
|
+
this.#tokenHelper("_cancel", token);
|
|
214
|
+
};
|
|
215
|
+
// One reaction (no finally: it would add two steps to every request).
|
|
216
|
+
const done = () => {
|
|
217
|
+
if (control)
|
|
218
|
+
control.cancel = undefined;
|
|
219
|
+
this.#pending.delete(token);
|
|
220
|
+
};
|
|
221
|
+
const settled = task.then((value) => {
|
|
196
222
|
try {
|
|
197
|
-
|
|
223
|
+
if (cancelled)
|
|
224
|
+
this.#tokenHelper("_discard", token);
|
|
225
|
+
if (value !== null)
|
|
226
|
+
return { value };
|
|
227
|
+
return { error: this.#withGIL(() => this.#withToken(token, (id) => this.#call("_take_failure", [id]))) };
|
|
198
228
|
}
|
|
199
229
|
finally {
|
|
200
|
-
|
|
230
|
+
done();
|
|
231
|
+
}
|
|
232
|
+
}, (error) => {
|
|
233
|
+
try {
|
|
234
|
+
if (error === CANCELLED)
|
|
235
|
+
return { error: this.#withGIL(() => this.#call("_cancelled_failure")) };
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
done();
|
|
201
240
|
}
|
|
202
241
|
});
|
|
242
|
+
this.#pending.set(token, settled);
|
|
243
|
+
return settled;
|
|
244
|
+
}
|
|
245
|
+
#tokenHelper(name, token) {
|
|
246
|
+
this.#withGIL(() => this.#api.Py_DecRef(this.#withToken(token, (id) => this.#call(name, [id]))));
|
|
247
|
+
}
|
|
248
|
+
/** `use` with the token as a Python int (GIL held). */
|
|
249
|
+
#withToken(token, use) {
|
|
250
|
+
const id = this.#check(this.#api.PyLong_FromLongLong(token));
|
|
251
|
+
try {
|
|
252
|
+
return use(id);
|
|
253
|
+
}
|
|
254
|
+
finally {
|
|
255
|
+
this.#api.Py_DecRef(id);
|
|
256
|
+
}
|
|
203
257
|
}
|
|
204
258
|
#call(name, args = []) {
|
|
205
259
|
const helper = this.#helpers.get(name);
|
|
@@ -225,107 +279,30 @@ export class PythonExecutor {
|
|
|
225
279
|
if (this.#namespace)
|
|
226
280
|
this.#api.Py_DecRef(this.#namespace);
|
|
227
281
|
}
|
|
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
282
|
close() {
|
|
297
283
|
this.#closing ??= this.#finish();
|
|
298
284
|
return this.#closing;
|
|
299
285
|
}
|
|
300
286
|
async #finish() {
|
|
301
|
-
await Promise.allSettled([...this.#pending.values()]
|
|
302
|
-
const outcome = await this.#dispatch(null, true);
|
|
287
|
+
await Promise.allSettled([...this.#pending.values()]);
|
|
303
288
|
try {
|
|
304
|
-
|
|
289
|
+
const [state, threadState] = await this.#attached;
|
|
290
|
+
// FIFO, after every accepted request: the thread state is released on
|
|
291
|
+
// its own thread, then the thread stops. Both are queued before waiting:
|
|
292
|
+
// between them the executor thread holds the GIL, and it must not wait
|
|
293
|
+
// for this thread, which may take the GIL meanwhile (e.g. stats()).
|
|
294
|
+
const restored = this.#restoreThread.callOn(this.#executor, threadState);
|
|
295
|
+
const released = this.#releaseState.callOn(this.#executor, state);
|
|
296
|
+
await Promise.all([restored, released]);
|
|
305
297
|
}
|
|
306
298
|
finally {
|
|
307
|
-
|
|
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
|
-
}
|
|
299
|
+
await this.#executor.close();
|
|
322
300
|
this.#withGIL(() => this.#releasePython());
|
|
323
|
-
this.#channel.release();
|
|
324
301
|
}
|
|
325
302
|
}
|
|
326
303
|
abandon() {
|
|
327
|
-
// Forced exit retains Python
|
|
304
|
+
// Forced exit retains Python owners until the OS tears down the process;
|
|
305
|
+
// node-ctypes leaves the executor thread to the process exit.
|
|
328
306
|
this.#abandoned = true;
|
|
329
|
-
this.#channel.unref();
|
|
330
307
|
}
|
|
331
308
|
}
|
package/dist/platform.d.ts
CHANGED
|
@@ -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>}
|