【问题标题】:Node.js running Python Script doesn't return correct results运行 Python 脚本的 Node.js 不返回正确的结果
【发布时间】:2019-08-02 00:10:41
【问题描述】:

我正在开发 Node.Js/Express 应用程序,需要从路由调用 python 脚本。

路线代码:

router.get ('/new_bids',async (req, res) => {
  const { spawn } = require('child_process');
  const pyprog = spawn('python',["public/pythonscripts/new_bids_alert.py"]);
  pyprog.stdout.on('data', function(results) {
      console.log('results: %j', results[0]) 
  });
  pyprog.stderr.on('data', (results) => {
      console.log('err results: %j', results) 
  });
}) 

Python new_bids_alert.py:

 import sys
 em = 2
 print(em)
 sys.stdout.flush()

我希望看到:

结果:2

但我明白了:

结果:50

console.log(results)

返回:

"缓冲区 32 0d 0a"

感谢您的帮助。

【问题讨论】:

    标签: python node.js stdout stdin spawn


    【解决方案1】:

    想通了。应该有用:

    JSON.parse(结果)

    代替:

    结果[0]

    【讨论】:

    • 我有同样的问题..我尝试使用 JSON.parse.. 但它抛出错误说...在位置 0 的 JSON 中出现意外标记 'O'...'O' 因为我的输出字符串来自 python 代码就像:'输出是这个......'你能告诉如何在 json 中发送结果吗?
    • @KSK。试试 JSON.parse(JSON.stringify(...))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2012-04-11
    • 2016-02-06
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多