Skip to content
Advertisement

exchanging data between node and Python with python-shell

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:UsersbbartlingDesktopjavascriptstouttest_SOapp.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.

Advertisement

Answer

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);
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement