node.js在收到时生成stdout字符串

时间:2013-07-30 00:46:19

标签: javascript node.js spawn child-process

我有以下python代码(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”时,我会得到类似的内容:

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以下列方式调用它时:

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'的东西打断了但是没有。不知何故,流被中断,即

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 ..)

有谁知道为什么会发生这种中断?

谢谢!

爱丽儿。

2 个答案:

答案 0 :(得分:0)

根据设计,console.log在输出结尾处写入换行符。

您可能希望改为使用process.stdout.write

http://nodejs.org/api/stdio.html#stdio_console_log_data http://nodejs.org/api/process.html#process_process_stdout

答案 1 :(得分:0)

正如上面adpalumbo所指出的,每个“块”都会调用事件数据。 通过在事件“关闭”发生后连接数据并采取措施来解决问题:

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,感谢您指出这一点!