Python 与正在运行的进程交互

标签 python linux

我有一个 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/

相关文章:

c - 当 tcp 在 close_wait 时,select 总是返回 1

linux - 任何人都可以帮助无法运行这个unix shell脚本吗?

python - PyQt:将项目从 ListView 拖放到 TableView 中,放置索引始终为-1

python - discord .py 的错误代码

python - 使用 pandas 查找是否有两列名称不同但值相同

linux - 在linux中根据搜索列显示整行的命令?

PHP ZipArchive 无法在 Windows 下运行的 Ubuntu Linux 上提取文件

linux - 在 Linux 中从网络摄像头获取视频流

python - Bootstrap Accordion 与 Django : How to only load the data for the open accordion section?

python - python中列表概念的列表