【问题标题】:How to communicate between NodeJS and Python (pynput) with child process如何使用子进程在 NodeJS 和 Python (pynput) 之间进行通信
【发布时间】:2020-06-12 22:04:39
【问题描述】:

我在 python 中编写了一个脚本,它使用 pynput 并在控制台中显示从键盘按下的键。

from pynput.keyboard import Listener

def on_press(key):
    try:
        print('keydown : {0}'.format(
            key.char))
    except AttributeError:
        print('keydown : {0}'.format(
            key))

def on_release(key):
    try:
        print('keyup : {0}'.format(
            key.char))
    except AttributeError:
        print('keyup : {0}'.format(
            key))


with Listener(on_press=on_press, on_release=on_release) as listener:  
    listener.join()

我指出我这辈子从来没有做过 python,而且这段代码在我运行它的时候就可以工作。 我们得到了预期的结果:

keydown : a
keyup : a
keydown : b
keyup : b
keydown : Key.enter
keyup : Key.enter

但是,我想用 NodeJS 在子进程中运行它:

const child = require('child_process')
var py = child.spawn('python3', ['myFile.py'])
py.sdout.on('data', (data) => { console.log(data.toString()) })
py.stderr.on('data', (data) => { console.error(data.toString()) })

但是当我使用 NodeJS 执行 javascript 文件时,当我按下一个键时,我没有收到任何数据或错误...但是我的子进程可以与任何其他 python 脚本一起使用...

如果有人知道我为什么不能这样做或知道解决方案,请提前感谢您的回复。

【问题讨论】:

  • 问题是您的 Python 脚本永远不会结束 Node.js 读取其输出。用print("Hello, World!") 替换您的脚本,您会看到它按预期工作。
  • 还有另一个问题:您没有将输入从父进程传送到其子进程,因此您的按键永远不会到达 Python 脚本。你需要像py.stdin.write('YOUR_INPUT) 这样的东西,然后是py.stdin.end()

标签: python node.js child-process pynput


【解决方案1】:

正如我在 cmets 中指出的那样,您的 Node.js 应用程序不会将其输入流传递给其子进程,其子进程也不会完成其父进程以读取其输出。所以这是一个有效的例子,但在完成之前只读取第一个按键:

Node.js(相同的脚本,但我们将按键通过管道传递给子进程):

const { spawn } = require('child_process');
const readline = require('readline');

const py = spawn('python3', ['/home/telmo/Desktop/myFile.py']);

readline.emitKeypressEvents(py.stdin);
process.stdin.setRawMode(true);

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

py.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

py.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

Python(相同的脚本,但我们在第一个按键事件之后完成):

from pynput.keyboard import Listener
import sys

def on_press(key):
    try:
        print('keydown : {0}'.format(
            key.char))
    except AttributeError:
        print('keydown : {0}'.format(
            key))

def on_release(key):
    try:
        print('keyup : {0}'.format(
            key.char))
        sys.exit()
    except AttributeError:
        print('keyup : {0}'.format(
            key))

with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

当我按下“a”时运行这些,我得到以下输出:

stdout: keyup : Key.enter
keydown : a
keyup : a

child process exited with code 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    相关资源
    最近更新 更多