簡體   English   中英

如何將Python連接到Node.js?

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

我想將一個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

有關:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM