Home > Back-end >  call python def function in nodejs
call python def function in nodejs

Time:12-13

i run a python script in nodejs . it works . But I want to stay open and then call the def function from nodejs several times. how can i do that.

nodejs

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


let py=PythonShell.run('test.py', null, function (err, results) {

  console.log('results: %j', results);
});

test.py

print('start');

def hello():
    print ('hello');

CodePudding user response:

Calling a specific function at runtime is not a supported functionality of the PythonShell library without configuring the target Python script to do so. For example, consider the following Python script file based on your current example:

print('start')

def hello():
    print ('hello')

if "say-hello" in sys.argv:
    hello()

You can pass the say-hello argument when invoking your script file from Node to execute this method as you seem to want to do:

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


let py=PythonShell.run('test.py', ["say-hello"], function (err, results) {
  console.log('results: %j', results);
});

CodePudding user response:

If im not mistaken, you want to run the python script seveal times?

put the let py=pythonShell... in a function and call that as many times as you want

  • Related