简体   繁体   English

如何从NodeJS调用无尽的python脚本

[英]How to call endless python script from NodeJS

I have a python script: 我有一个python脚本:

//test.py

import psutil

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

and then nodejs code: 然后是nodejs代码:

//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. 请帮助我如何每秒从Node的无尽python代码获取数据(例如“实时”)并将其记录到控制台。

You need to flush STDOUT: 您需要刷新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 看起来这是python-shell npm包的常见问题-https: //github.com/extrabacon/python-shell/issues/81

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM