如何在后台启动子进程并通过按键停止它?

How to launch a subprocess in the background and stop it by pressing a key?

我在 Windows 10,使用 Python 3.7,我想启动一个子进程来读取视频并在用户触摸键盘时停止它(我正在使用 keyboard 来自 https://pypi.org/project/keyboard 的模块):

import subprocess
import keyboard

p1 = subprocess.call(keyboard.record(until='enter'))
p2 = subprocess.call([vlc, url_video, "vlc://quit", "&", "exit 0"])
while True:
    if p1.poll():
        p2.terminate()
        break
    if p2.poll() == None:
        break

问题是启动 p1 不会 return,并且会阻止 p2 的启动。所以我从来没有进入死循环。

这段代码至少有两个问题:

  • subprocess.call(keyboard.record(until='enter')) 首先调用 keyboard.record 阻塞直到 return 秒,然后 然后 调用 subprocess.callkeyboard.record 的 return 值作为参数(这本身没有意义)。

  • subprocess.call 也会阻塞,直到启动的子进程完成(除了在这里没有做你想做的事情,它自 Python 3.5 以来也已过时。)。我们可以使用 subprocess.Popenbackground.

    中启动一个子进程

你用的不是keyboard API effectively. You do not want to record the keystrokes while the video recording is running, you want to trigger an action if a specific key is pressed. For this, the on_press_key功能好像比较合适

它采用函数(回调),一旦按下特定的键就会执行该函数。我们可以传递一个函数来终止我们启动的子进程。

据我所知,这应该有效:

import subprocess
import keyboard

# I haven't checked if these arguments are correct, they are unchanged
p = subprocess.Popen([vlc, url_video, "vlc://quit", "&", "exit 0"])

# set up callback to kill vlc if key is pressed
def stop_vlc(event):
    if p.poll() is not None:
        return  # already done, do nothing
    p.terminate()

keyboard.on_press_key('enter', stop_vlc)

# wait until vlc finishes, either by itself or because it is killed
p.wait()