python - 无法更改 spawn 从 nodeJS 发送到 Python 的整数

标签 python node.js

我正在尝试如何从 NodeJS 运行 python,并在线找到了 child_process 生成解决方案。

// server setup constant
const express  = require('express');

// The application
const app = express();

// Port the server runs on
const port = 8080;

app.listen(port, () => console.log("running (main.js)"));


const spawn = require('child_process').spawn;
const py = spawn('python', ['main.py', "Message", 12]);


py.stdout.on('data', data => {
    console.log(data.toString());
});

py.stdout.on('end', () => {
    console.log("end of transmission");
});

我发送的第二个参数是整数 12。我尝试在 python 脚本中递增该数字,然后将其打印回来。奇怪的是,如果我更改作为参数从 Node 传输到 Python 的字符串,就没有问题。如果我尝试改变任何数量的Python崩溃。数字是否作为常量传输,这就是为什么?如果是这样,我该如何解决这个问题?

Python:

import sys, json as np

message = sys.argv[1]
number = sys.argv[2]

number = number + 1

print(message)
print("Added one to number")
print(number)


sys.stdout.flush()

最佳答案

sys.argv 是字符串列表。使用 int() 函数将字符串转换为数字。

import sys, json as np

message = sys.argv[1]
number = int(sys.argv[2])  # convert string to number

number = number + 1

print(message)
print("Added one to number")
print(number)


sys.stdout.flush()

关于python - 无法更改 spawn 从 nodeJS 发送到 Python 的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52078522/

相关文章:

python - 向 Redis 组 SADD 添加许多值

Python:如何根据 if 语句的结果将元素输出到特定的列和行

python - 使用 pyodbc 将日期时间插入到 MS SQL 表中

javascript - 从 HTTP GET 请求中获取数据

javascript - Node.js 相同的 uri 但不同的参数

node.js - 如何在ubuntu中安装appium。我有以下错误如何解决此错误我是 Node js 新手

node.js - 亚马逊MWS有REST版本API吗?

python - Windows下用Python复制文件

python - 如何检索两个字段值与 pymongo 相等的所有文档?

python - 检查 gdb pretty-print 中的内存