【问题标题】:Python to NodeJS communication not working through spawnPython 到 NodeJS 的通信无法通过 spawn 进行
【发布时间】:2021-06-16 06:15:32
【问题描述】:

我正在尝试复制此过程以通过 stdin 和 stdout 建立 nodejs 和 python 的通信:https://healeycodes.com/javascript/python/beginners/webdev/2019/04/11/talking-between-languages.html

背景: 发件人 - 向标准输出提供输出

听众 - 正在阅读的人

现在,当 Python 是发送者而 NodeJS 是侦听器时,它不起作用。 NodeJS 没有输出。 进一步挖掘我的问题与Not receiving stdout from nodejs spawned process 非常相似,只是我不需要这样的无缓冲输出。从上一个问题中尝试过 sol.. 没有用。

这里是文件: 传感器.py

import random, time
import sys

time.sleep(random.random() * 5)  # wait 0 to 5 seconds
temperature = (random.random() * 20) - 5  # -5 to 15
print(temperature, flush=True, end='')
sys.stdout.flush()

listener.js

const { spawn } = require('child_process');

//spawn()
const child = spawn('python', ['path-to-sensor.py']);
console.log('Here');

child.stdout.on('data', function(data) {
    console.log('Got the data')
    console.log(data)
  });
  child.on('error', function () {
    console.log("Failed to start child.");
  });
  child.on('close', function (code) {
    console.log('Child process exited with code ' + code);
  });
  child.stdout.on('end', function () {
    console.log('Finished collecting data chunks.');
  });

原因:事件监听器 - child.stdout.on('data', callback) 永远不会被调用

我想要的输出是: 将 sensor.py 中的标准输出存储在变量中

不知道我还能做些什么来解决这个问题

【问题讨论】:

    标签: javascript python node.js debugging


    【解决方案1】:

    在 sensor.py 中,您没有在代码中使用正确的语法:

    print(temperature, flush=True, end='')
    

    正确的语法是:

    print(object(s), sep=separator, end=end, file=file, flush=flush)
    

    Source

    如果您将 sensor.py 中的代码保留为:

    print(temperature)
    

    在 listener.js 中为:

    child.stdout.on('data', function(data) {
        console.log('Got the data')
        //console.log(data)
        console.log(data.toString('utf8'))
     });
    

    一切正常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      相关资源
      最近更新 更多