繁体   English   中英

如何从Python加载数据并保存到JavaScript中的变量

[英]How to load data from Python and save to a variable in JavaScript

我正在做一个项目,我需要在 Python 中使用一些库,但是,该项目的大部分将在 Javascript (React Native) 中编码。

我目前正在玩从 JavaScript 调用 Python,我想将从 Python 调用的数据保存到我的 JavaScript 文件中的变量。

这是我目前正在玩的代码:

索引.js

const spawn = require("child_process").spawn;

const process = spawn("python", ["./hello.py", 4]);

var result;

process.stdout.on("data", (data) => {
  result = parseInt(data.toString());
});

var newNum = result * 10;
console.log(newNum);

你好.py

import sys

sum = 0
sum = int(sys.argv[1])
sum = sum*3

print(sum)

但是,控制台 output 只是“未定义”,我该怎么做才能解决这个问题?

谢谢

由于 Node.js 是异步的,因此在尝试对result进行操作之前,您需要等待子进程退出。 让我举例说明:

const spawn = require("child_process").spawn;
const process = spawn("python", ["./hello.py", 4]);
// A process was started in the background, and your code continues...
// You declare a `result` variable, whose value is `undefined`...
var result;
// Python might still be starting up at this point...
// You register a handler for output from the process, but it might not get called
// yet since your computer is from 1996 and it takes a while to start Python...
process.stdout.on("data", (data) => {
  result = parseInt(data.toString());
});
// You operate on the `result`, which still is undefined...
var newNum = result * 10;
// Oh! Hey! Python started in the background! It printed out some data, and now the data handler from before got called! Yay! `result` is indeed 12 right now!
// but... you know... let's print `undefined * 10`.
console.log(newNum);

您可以等待标准输出 stream 结束:

const spawn = require("child_process").spawn;

const process = spawn("python", ["./hello.py", 4]);

var result;

process.stdout.on("data", (data) => {
  result = parseInt(data.toString());
});

process.stdout.on("end", () => {
  var newNum = result * 10;
  console.log(newNum);
});

或者退出的过程:

const spawn = require("child_process").spawn;

const process = spawn("python", ["./hello.py", 4]);

var result;

process.stdout.on("data", (data) => {
  result = parseInt(data.toString());
});

process.on("exit", () => {
  var newNum = result * 10;
  console.log(newNum);
});

您可以将其包装成一个简洁的助手 function,它返回 promise(抱歉,未经测试):

const spawn = require("child_process").spawn;

function spawnAndCaptureOutput(command, args) {
  return new Promise((resolve) => {
    const process = spawn(command, args);
    let stdout = "";
    let stderr = "";
    process.stdout.on("data", (data) => {
      stdout += data.toString();
    });
    process.stderr.on("data", (data) => {
      stderr += data.toString();
    });
    process.on("close", (code) => {
      resolve({ stdout, stderr, code });
    });
    // TODO: error handling?
  });
}

spawnAndCaptureOutput("python", ["./hello.py", 4]).then(
  ({ stdout }) => {
    const number = parseInt(stdout);
    console.log(number * 8);
  },
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM