0

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.

2 Answers 2

0

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you that worked at least Node doesnt crash. Any chance you could help me write the scripts to call the get_time and get_weekday python functions and see the results in Javascript console.log('results: %j', results);
updated my answer...I'd suggest you checkout python-shell's documentation to know about more advanced usage. Link: npmjs.com/package/python-shell
Would you have any tips for this similar question? stackoverflow.com/questions/70511960/…
0

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)}") 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.