如何将Python连接到Node.js?

时间:2018-09-16 02:13:30

标签: javascript python variables flask

我想将一个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之间循环变量?

1 个答案:

答案 0 :(得分:1)

这是一种实现方法,方法是从节点内部生成子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

相关: