我有一个 python 脚本,它允许我使用简单的网络服务器 (Flask) 从我的手机与我的 Rapsberry Pi 进行交互。
在此脚本中,我可以调用 omxplayer 来播放媒体文件,我通过如下命令执行此操作:
Popen(['omxplayer '+filePath], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
这工作正常,但我希望能够通过发送键命令与此过程进行交互。当 omxplayer 正在运行时,您可以按空格键播放/暂停,按箭头键向前/向后跳过等。我想从我的 python 脚本中以编程方式发送这些键盘输入,而不是要求一个人在键盘上手动按下它们。
如何在使用 Python 打开此进程后从 Python 向该进程发送关键命令?
另外,如果有另一个正在运行的 omxplayer 实例不是当前正在从此 Python 脚本运行,我如何从 Python 检测?例如,如果 omxplayer 被调用并从某人通过 ssh 连接运行,我如何在 python 脚本中检测到它并在调用我自己的 omxplayer 进程之前终止该进程?
最佳答案
听起来 omxplayer 正在从 stdin 读取 - 您可能可以使用您的命令写入该进程的 stdin。
from subprocess import Popen, PIPE
p = Popen(['omxplayer', filePath], stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
p.stdin.write(' ') # sends a space to the running process
p.stdin.flush() # if the above isn't enough, try adding a flush
编辑:要发送箭头键,请在终端中尝试 Ctrl+v 和 ← 以查看正在发送的键码 -它将是 ^[[D
,或 esc[D。您可以使用 stream.write("\x1b[D")
(或 "^[[D"
,其中 ^[
是 Ctrl+v esc 并等待半秒产生的一个字符)。
关于Python 与正在运行的进程交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20762233/