nodejs python 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: stop python script nodejs
var python_process;
router.get('/start_python', function(req, res) {
var PythonShell = require('python-shell');
var pyshell = new PythonShell('general.py');
pyshell.end(function (err) {
if (err) {
console.log(err);
}
});
python_process = pyshell.childProcess;
res.send('Started.');
});
// this stops the process
router.get('/stop_python', function(req, res) {
python_process.kill('SIGINT');
res.send('Stopped');
});
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:])
Example 4: python node
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def PrintTree(self):
print(self.data)
root = Node(10)
root.PrintTree()