1

我有以下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 ..)

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

谢谢!!

爱丽儿。

4

2 回答 2

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

于 2013-07-30T00:51:41.643 回答
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,感谢您指出这一点!

于 2013-07-30T21:31:25.600 回答