收到时,node.js生成标准输出字符串已损坏 [英] node.js spawn stdout string broken when received

查看:46
本文介绍了收到时,node.js生成标准输出字符串已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下python代码(script.py):

I have the following python code (script.py):

import sys
import numpy as np
from scipy import stats

def generateBeta() :
    fit = (0.075252656968743836, 498.49505071718869, 9.9999999999999991e-05, 0.18136881492296397)
    rnd = stats.beta.rvs(fit[0], fit[1], fit[2], fit[3], 581)
    rndStr = ""
    for i in rnd:
            rndStr += str(i) + ','
    print rndStr[0:len(rndStr)-1]

if __name__ =='__main__' :
    generateBeta()

运行"python script.py"时,我得到类似的东西:

When running "python script.py" I get something like:

0.000461650100253,0.000100731728317,0.000106550237062,0.000168159408577,0.000167330103757,0.000100050650386,0.000127253399976,0.000100193300275,0.000101258755861,0.000115222086572,0.00010000230276,....

0.000461650100253,0.000100731728317,0.000106550237062,0.000168159408577,0.000167330103757,0.000100050650386,0.000127253399976,0.000100193300275,0.000101258755861,0.000115222086572,0.00010000230276, ....

全部一行

当我通过以下方式使用node.js child_process#spawn调用它时:

When I call it using node.js child_process#spawn in the following way:

var sys   = require('sys'),
    spawn = require('child_process').spawn,
    pyScript = spawn('python', ['./script.py']);
pyScript.stdout.setEncoding('utf8');
pyScript.stdout.on('data', function (data) {
  console.log(data);
});

数字被看起来像'\ n'的东西打断,但不是.流以某种方式被中断,即

The numbers get interrupted by something looking like a '\n' but is not. Somehow the stream is interrupted, i.e.

0.000461650100253,0.000100731728317,0.000106550237062,0.000168159408577,0.000167330103757,0.000100050650386,0.000127253399976,0.000100193300275,0.000101258755861,0.000115222086572,0.00010000230276,...

0.000461650100253,0.000100731728317,0.000106550237062,0.000168159408577,0.000167330103757,0.000100050650386,0. 000127253399976,0.000100193300275,0.000101258755861,0.000115222086572,0.00010000230276, ...

这会导致在解释数据时出错(即导致0.000127之后被解释为127.)

Which derives to an error on interpreting the data (i.e., causes 0.000127 later being interpreted as 127..)

有人知道为什么会发生这种干扰吗?

Does anyone knows why such interruption occurs??

谢谢!

爱丽儿.

推荐答案

正如adpalumbo指出的那样,每个块"都将调用事件数据.通过连接数据并在发生关闭"事件后采取措施来解决该问题:

As pointed above by adpalumbo, the event data is called for every "chunk". The problem is solved by concatenating data and taking action after the event 'close' occurs:

var allData = "";
   pwScript.stdout.on('data', function (data) {
      allData = allData.concat(data);
   });

pyScript.on('close', function () {
  allData.split(',').forEach(function(d) { process.stdout.write(d + '\n')});
});

adpalumbo,感谢您指出这一点!

adpalumbo, thanks for pointing this out!

这篇关于收到时,node.js生成标准输出字符串已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆