繁体   English   中英

与服务器上运行的 python 脚本保持通信

[英]Keep comunication with python script running on server

这是我迄今为止开发的。 首先,我的websocket服务器:

// app.js
const spawn = require('child_process');
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection',ws => {
  ws.on('message', message => {
    const python = spawn('python', ['-u', 'main.py', message])
    python.stdout.on('data', function (data) {
      // Pipe data from python script ...
      dataToSend = data.toString('utf8');
      ws.send(dataToSend)
     });
     python.on('error', err => {
       console.log(err)
     })
  })
  ws.on('close', () => {
    console.log('Client has disconected')
  })
}).on('error', err => {
  console.log(err)
})

它基本使用child_process生成 python 脚本,传递从客户端发送的message -u被传递以刷新 python 脚本打印,因此它可以在python.stdout上流出并发送到客户端。

这是从 app.js websocket 服务器调用的我的 python 脚本:

# main.py
import time, sys
i = int(sys.argv[1])
while i > 0:
    print(i)
    i-=1
    time.sleep(1)
    # this while is just anexemple of some pre-script process
    # (for exemple, signin on user account)

# after signin...
print('input something from client: ')
x = input()

while True:
    print(x)
    time.sleep(1)
    # use input x variable
    # here is where my code happens and the program keeps executing
    pass

如您所见,我正在使用从服务器传递给spawn()messagewhile我的第一个状态。 这只是一个例子,我需要用户的这种输入。

请注意x = input()因为这是我的主要问题

最后,我的客户 websocket

// client.js
const WebSocket = require('ws');
let socket = new WebSocket("ws://localhost:8080");

socket.onopen = function(e) {
    let someClientInfo = 2
    console.log("sending data...");
    socket.send(someClientInfo);

};

socket.onmessage = function(event) {
    console.log('Output of python script: ' + event.data.toString('utf-8'));
};

socket.onerror = function(event) {
    console.log(event);
};

它基本传递第一个参数someClientInfo ,然后像这样接收 python 脚本 output :

sending data...

Output of python script: 2 

Output of python script: 1

Output of python script: input something from client:

当然,当客户收到最后一行时,它会一直卡住,因为他无法从他那里输入任何内容。 他刚刚收到来自 python 的输出 stream。

任何人都知道是否可以将第二个输入传递给我正在运行的 python 脚本? 我开始认为这可能是不可能的,但我不能考虑另一种方法来做到这一点。 如果是child_process不能做的事情,我应该寻找什么方法?

我的主要目的是与服务器上运行的 python 脚本保持有效通信,因此我可以将此输入从客户端传递给 python。

我希望能够从此套接字断开连接,然后再次连接并继续接收 python 脚本输出。 到目前为止,我也找不到这样做的方法。

我的主脚本不能在服务器代码中(也许如果你对 flask 的基本实现或类似的东西有兴趣的话),因为我希望能够启动多个脚本并且每个客户端用户应该能够保持迭代他自己的 python 脚本在服务器上运行。 每个用户都有自己的main.py

到目前为止,我还没有考虑如何让所有这些进程在服务器上运行,或者即使这样做是安全的。 对此的任何建议都会非常感激,我也会非常感激。

您可能想查看https://www.npmjs.com/package/python-shell您可以在节点上生成 python 实例。

暂无
暂无

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

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