Home > database >  exchanging data between node and Python with python-shell
exchanging data between node and Python with python-shell

Time:12-29

I am trying to learn how to exchange data between Node and Python with python-shell, on the git repo they have some example code:

Borrowing some of this code, this is app.js:

import {PythonShell} from 'python-shell';

let options = {
  mode: 'text',
  args: ['get_time()', 'get_weekday()']
};

PythonShell.run('my_script.py', options, function (err, results) {
  if (err) throw err;
  // results is an array consisting of messages collected during execution
  console.log('results: %j', results);
});

And this is my_script.py below that will just print the weekday and current time:

from datetime import datetime

# Create datetime object
date = datetime.now()

# Get the weekday value, as an integer
date.weekday()

# Define a list of weekday names
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']


def get_weekday():  
    return days[date.weekday()]


def get_time():
    return datetime.now().time()

#print(get_time())
#print(get_weekday())

When run app.js this throws an error:

(node:15380) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
Uncaught c:\Users\bbartling\Desktop\javascript\stout\test_SO\app.js:1
import {PythonShell} from 'python-shell';
^^^^^^

SyntaxError: Cannot use import statement outside a module
No debugger available, can not send 'variables'
Process exited with code 1

Any ideas to try? Thanks for any tips not a lot of wisdom here. Can I call these functions on the Python script through python-shell? Just curious if I could use Javascript with this python-shell package to retrieve either the current weekday or current time from Python.

CodePudding user response:

Replace import {PythonShell} from 'python-shell'; with let {PythonShell} = require('python-shell');

Edit: In .py file, import sys and then the arguments passed from nodejs will be available in sys.argv as array. I suppose by putting if checks you can call specific functions and at the end whatever you print in python would be available in results in js

Sample:

.py file:

import sys

def log():  
    print('hello from python')
    
if sys.argv[1][0]=="1":
    log()

.js file:

let { PythonShell } = require("python-shell");

let options = {
  mode: "text",
  args: "1",
};

PythonShell.run("my_script.py", options, function (err, results) {
  if (err) throw err;
  // results is an array consisting of messages collected during execution
  console.log("results: %j", results);
});

CodePudding user response:

Thanks to @sandeep.kgp getting me started here's a complete answer thanks to the help of a YouTube video for python-shell. The code below will just pass some values back and forth checking current time with 2 different python pacakges.

app.js

let {PythonShell} = require("python-shell");

let options = {
  mode: "text",
  args: ["datetime","time"],
};

PythonShell.run("my_script.py", options, function (err, results) {
  if (err){
    console.log(err)
    console.log("An error happened")
  }else{
      // results is an array consisting of messages collected during execution
    console.log("results: ", results);
    console.log("Python Script Finished");
    }
})

my_script.py

import sys, time
from datetime import datetime


date = datetime.now()
today = date.today()
today.strftime("%d/%m/%Y")


def use_datetime():  
    print("Using datetime package its: ", today)


def use_time():
    print("Using the time package its: ", time.ctime())


try:
    for arg in sys.argv:
        #print(arg)
            
        if arg == "time":
            use_time()

        elif arg == "datetime":
            use_datetime()

        else:
            print("An arg passed: ", arg)

except Exception as error:
    print(f"Error: {str(error)}") 
  • Related