alextran
alextran

Reputation: 161

How to call endless python script from NodeJS

I have a python script:

//test.py

import psutil

while True:
    result = psutil.cpu_percent(interval=1)
    print(result)

and then nodejs code:

//test.js
    var PythonShell = require('python-shell')
    pyshell = new PythonShell('test.py')
    pyshell.on('message', function(message) {
        console.log(message)
    })

nothing happened when I executing node script. Please help me how to get data per second (like "real-time") from endless python code from Node and loggging it to console.

Upvotes: 0

Views: 280

Answers (1)

timborden
timborden

Reputation: 1480

You need to flush STDOUT:

#test.py

import psutil
import sys

while True:
    result = psutil.cpu_percent(interval=1)
    print(result)
    sys.stdout.flush()

It looks like it's a common issue with the python-shell npm package - https://github.com/extrabacon/python-shell/issues/81

Upvotes: 1

Related Questions