Call Python code from Javascrip code that runs on Node.js. I also want Javascript code to receive the output of Python code and process the received data on Javascript.
Use Python-shell. Click here for Python-shell source
Explains the preparation and installation method for using Python-shell. It is assumed that node.js and python are already installed.
environment ・ Ubuntu 18.04 on Raspberry pi4 (Docker) ・ Because. js v12.14.0 ・ Npm 6.13.4
Install python-shell using npm.
python
root@24f85fb6fd69:/home# npm install python-shell
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
+ [email protected]
updated 1 package and audited 103 packages in 2.37s
found 0 vulnerabilities
Create a directory TEST and place test.js and sample.py with the following code.
/home/pi/test/test.js
var {PythonShell} = require('python-shell');
//Create an instance of PythonShell, pyshell. The python file name to call from js is'sample.py'
var pyshell = new PythonShell('sample.py');
//From js to python code'5'Is provided as input data
pyshell.send(5);
//Data is passed from python to js after executing the python code.
//The data passed to python is stored in "data".
pyshell.on('message', function (data) {
console.log(data);
});
/home/pi/test/sample.py
import sys
data = sys.stdin.readline() #Get data from standard input
num=int(data)
def sum(a):
return a+3
print(sum(num)) #print()The contents of are passed to js.
/home/pi/test/
root@24f85fb6fd69:/home/test# node test.js //test.Run js
8 //The result processed by python is passed to javascript and executed.
I tried according to Python-shell source, but JSON format error "unexpected token T in json at position 1" is output everywhere. It doesn't work and traces, but there seems to be little information about Python-shell. So, I tried to send JSON data from Javascript to Python via a JSON file created separately, and it worked.
The code is posted below.
/home/pi/test/test.js
const PYPATH="sample.py"
var {PythonShell} = require('python-shell');
var pyshell = new PythonShell(PYPATH, { mode: 'text'}); //mode is "JSON]It is better to specify "text" instead.
//(1-1)Store the brand data to be registered in the dictionary type array.
var obj={
stock_num: 2145,
c_name:"ABC_COMPANY",
eps:100
}
//(1-2)The dictionary type array is converted to JSON format.
var jsondat = JSON.stringify( obj );
//(1-3)If the file to write the above jsondat already exists, delete the file once.
if (fs.existsSync(JSONFILEPATH)) fs.unlinkSync(JSONFILEPATH)
//(1-4)If the file to write the above jsondat already exists, delete the file once.
fs.writeFileSync(JSONFILEPATH,jsondat)
//(2)Send empty data from js to python code. To launch python code
pyshell.send("");
//(4)Receive Python execution results
pyshell.on('message', function (data) {
console.log(data)
res.send({
message: "success" //The result of the operation performed by python is returned to the front end.
})
})
/home/pi/test/sample.py
import sys
import json
#(3-1)JSON file test.open json
f = open('test.json', 'r')
#(3-2)test.Read json data
json_dict = json.load(f)
#(3-3)JSON data json_dict key:'stoch_num'To access.
dat1=json_dict['stock_num']
print(dat1) #print contents python-Return to shell
/home/pi/test/test.json
{"stock_num":"2145","c_name":"ABC company","eps":"100"}
Recommended Posts