pytalk.js
Pytalk is a module for bidirectional communication between Node and Python.
It lets you create Python process, and communicate with it via standard streams. Every message passed through pytalk gets serialized into JSON.
Before starting the process, Pytalk modifies the Python code, instantiating an event loop and allowing you to send and recieve messages with pytalk_emit
, pytalk_on
or registering Python method with pytalk_method
.
Install
Install through npm
npm install pytalk
Usage
- Using a worker script, calling registered Python method asynchronously
indexjs | workerpy------------------------------------------------------------------------------------------------const pytalk = ; | | | let worker = pytalk; | @let blur = workermethod'blur'; | def : | img = cv2; | return dst
- Importing modules using proxy PyObjects.
const pytalk = ; let worker = pytalk; // Create Python process let math = worker // Load modules os = worker np = worker; math // 3628800ospath // ['aaa', 'bbb'] let arr = np // PyObject instancearr = np // still PyObject instancearr // [2, 3, 4]
Note that objects proxied by PyObjects don't get garbage collected by Python. You can unreference them manually using unrefAll()
.
Documentation
new Worker([scriptPath], [options])
or, which is the same pytalk.worker(scriptPath, options)
scriptPath
path to the Python script.
options
pythonPath
- path to the Python binary. Default ispython
.stdout
- callback called when Python script prints something. Default isconsole.log
.stderr
- callback called on Python's raised errors. Default isconsole.log
.async
- If true, PyObject's methods become async. Default isfalse
. (example)
Worker.method(methodName)
Returns a function(arg1, ..., argN, callback)
. args
are the args passed to the Python method, registered using @pytalk_method(methodName)
decorator. callback
is a error-first function, called when Python method finishes its work. Use this when you need async version of some sync Python function.
Worker.methodSync(methodName)
Same thing as Worker.method
, except it waits until Python method gets its work done, and returns whatever Python function returns. Uses deasync under the hood.
Worker.on(eventName, callback)
Registers event handler for eventName
. callback
gets triggered with (err, args)
passed every time pytalk_emit(eventName, args)
is called in Python code.
Worker.emit(eventName, ...args)
Calls Python function, registered with @pytalk_on(eventName)
decorator, or through pytalk_on(eventName, callback)
Worker.close()
Sends exitSignal to Python's event loop. Worker closes as soon as it finishes its current job.
Worker.unrefAll()
Removes all references to Python objects, proxied by JavaScript objects. This allows Python GC to free resources if it needs to.
Worker.import(moduleName)
Imports moduleName in Python, and returns a proxy PyObject.
License
MIT