当前位置: 代码迷 >> python >> 如何将Python连接到Node.js?
  详细解决方案

如何将Python连接到Node.js?

热度:110   发布时间:2023-06-19 09:29:24.0

我想将一个node.js变量发送给python,使用python对其进行修改,然后将其重新发送至node.js,这是我的代码示例:Python

def change_input(variable):
    variable*=5
    #now send variable to node.js

现在的js代码:

var variable=prompt("enter the variable");
#after the code was sended to thd python code, modified and resend:
document.write(variable)

如何在python和javascript之间循环变量?

这是一种实现方法,方法是从节点内部生成一个子python进程。

test.js:

const { spawn } = require('child_process');
const p = spawn('python', ['yourscript.py', '1']);

p.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

yourscript.py

import sys

def change_var(x):
    print('hello from python: {:d}'.format(int(x) + 2))

change_var(sys.argv[1])

正在运行的node ./test.js输出:

stdout: hello from python: 4

目录布局

?  test tree
.
├── test.js
└── yourscript.py

0 directories, 2 files

有关:

  相关解决方案