tx8087 2022-12-04 01:12 采纳率: 100%
浏览 41
已结题

nodejs child_process通信问题

nodejs child_process通信问题

现有两个文件,且在同一目录下

test.py

print("py 启动")
x = input()
if(x == "1"):
    print("recived!")

index.js

const {
  exec
} = require("child_process")
const test = exec("python test.py", {
  cwd: process.cwd()
})

test.stdin.write("1")
test.stdout.on("data", (data) => {
  console.log(data.toString());
})

index.js代码写的有问题,要求就是用index去执行python脚本,且往脚本里面输入1。并打印出结果,test.py代码不可改动,index.js代码随便改,换个库都行,只要实现下效果。

执行node index,index.js调用python脚本,并往里面输入了1,并打印出结果

py 启动
1
recived!
  • 写回答

4条回答 默认 最新

  • 游一游走一走 2022-12-04 10:09
    关注
    var spawn = require('child_process').spawn,
        py = spawn('python', ['test01.py']),
        dataString = '';
    
    py.stdout.on('data', function (data) {
        dataString += data.toString();
    });
    py.stdout.on('end', function () {
        console.log(dataString);
    });
    py.stdin.write('1');
    py.stdin.end();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 12月12日
  • 已采纳回答 12月4日
  • 赞助了问题酬金20元 12月4日
  • 创建了问题 12月4日

悬赏问题

  • ¥15 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容