How to use Python-shell

1. Purpose

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.

1.JPG

2. Means

Use Python-shell. Click here for Python-shell source

3. Preferences and installation

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

3-1 Installation method

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

3-2 Usage example

Create a directory TEST and place test.js and sample.py with the following code.

2.JPG

/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.

3-3 execution

/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.

3.JPG

4 When sending JSON data to Javascript → Python

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.

15.JPG

/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

How to use Python-shell
How to use xml.etree.ElementTree
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to use shogun
How to use Pandas 2
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
Understand how to use django-filter
How to use the generator
[Python] How to use list 1
How to use FastAPI ③ OpenAPI
How to use Python argparse
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
Python: How to use pydub
[Python] How to use checkio
[Go] How to use "... (3 periods)"
How to use Django's GeoIp2
[Python] How to use input ()
How to use the decorator
[Introduction] How to use open3d
How to use Python lambda
How to use Jupyter Notebook
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Google Colaboratory
How to use Python bytes