run python script in node js code example
Example 1: child process spawn python node js
const path = require('path')
const {spawn} = require('child_process')
/**
* Run python myscript, pass in `-u` to not buffer console output
* @return {ChildProcess}
*/
function runScript(){
return spawn('python', [
"-u",
path.join(__dirname, 'myscript.py'),
"--foo", "some value for foo",
]);
}
const subprocess = runScript()
// print output of script
subprocess.stdout.on('data', (data) => {
console.log(`data:${data}`);
});
subprocess.stderr.on('data', (data) => {
console.log(`error:${data}`);
});
subprocess.stderr.on('close', () => {
console.log("Closed");
});
Example 2: how to make a python node
class Node:
def __init__(self, value, link_node=None):
self.value = value
self.link_node = link_node
def set_link_node(self, link_node):
self.link_node = link_node
def get_link_node(self):
return self.link_node
def get_value(self):
return self.value
Example 3: child process spawn python node js
import sys, getopt, time
def main(argv):
argument = ''
usage = 'usage: myscript.py -f <sometext>'
try:
opts, args = getopt.getopt(argv,"hf:",["foo="])
except getopt.GetoptError:
print(usage)
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print(usage)
sys.exit()
elif opt in ("-f", "--foo"):
argument = arg
print("Start : %s" % time.ctime())
time.sleep( 2 )
print('Foo is')
time.sleep( 2 )
print(argument)
print("End : %s" % time.ctime())
if __name__ == "__main__":
main(sys.argv[1:])