简体   繁体   English

如何将Python连接到Node.js?

[英]How to connect Python to Node.js?

I want to send to python a node.js variable, modify it with python and resend it to node.js, that is an example of my codes: Python 我想将一个node.js变量发送给python,使用python对其进行修改,然后将其重新发送至node.js,这是我的代码示例:Python

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

Now the js code: 现在的js代码:

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

How to circulates the variables between python and javascript? 如何在python和javascript之间循环变量?

Here is one way to do it, by spawning a child python process from within node. 这是一种实现方法,方法是从节点内部生成一个子python进程。

test.js: 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 yourscript.py

import sys

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

change_var(sys.argv[1])

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

stdout: hello from python: 4

directory layout 目录布局

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

0 directories, 2 files

related: 有关:

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

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