Popen.kill() 失败

Popen.kill() failing

更新 2:所以我通过管道传输了 stderr 的输出,当我包含 shell=True 时,我只是得到了 omx 播放器的帮助文件(它列出了所有命令行开关等) .有没有可能 shell=True 不能很好地与 omxplayer 一起播放?

更新:我之前遇到过 link 但它对我失败了所以我继续前进而没有深入挖掘。在 Tshepang 再次提出建议后,我进一步研究了它。我有两个问题,我希望第一个问题是由第二个问题引起的。第一个问题是,当我将 shell=True 作为参数包含在内时,视频永远不会播放。如果我不包括它,视频会播放,但不会被杀死。更新了下面的代码。

所以我正在尝试为我的 raspberry pi 编写一个 python 应用程序来循环播放视频(我发​​现 Popen 是使用 OMXplayer 完成此操作的好方法)然后继续键盘中断,它会终止该进程并打开另一个进程(播放不同的视频)。我的最终目标是能够将 vid1 作为一种 "screensaver" 使用,并在用户与系统交互时播放 vid2,但现在我只是试图在键盘输入和 运行 中杀死 vid1很难做到。我希望有人能告诉我我的代码哪里出错了。

预先警告,我对 Python 和一般基于 linux 的系统非常陌生,所以如果我这样做非常错误,请随时重定向我,但这似乎是到达那里的最快方式。

这是我的代码:

import subprocess
import os
import signal

vid1 = ['omxplayer', '--loop', '/home/pi/Vids/2779832.mp4']

while True:
    #vid = subprocess.Popen(['omxplayer', '--loop',     '/home/pi/Vids/2779832.mp4'], stdout=subprocess.PIPE, shell=True,     preexec_fn=os.setsid)
    vid = subprocess.Popen(vid1, stdout=subprocess.PIPE, preexec_fn=os.setsid)
    print 'SID is: ', preexec_fn
    #vid = subprocess.Popen(['omxplayer', '--loop',     '/home/pi/Vids/2779832.mp4'])
    id = raw_input()
    if not id:
        break
    os.killpg(vid.pid, signal.SIGTERM)
    print "your input: ", id
print "While loop has exited"

So I am trying to write a python app for my raspberry pi that plays a video on a loop (I came across Popen as a good way to accomplish this using OMXplayer) and then on keyboard interrupt, it kills that process and opens another process (playing a different video).

默认情况下,SIGINT 传播到前台进程组中的所有进程,请参阅 "How Ctrl+C works"preexec_fn=os.setsid(或os.setpgrp)实际上阻止了它:仅当您不希望omxplayer接收Ctrl+C时才使用它,即,如果当您需要终止进程树时,您手动调用 os.killpg(假设 omxplayer 子进程不更改他们的进程组)。

"keyboard interrupt"(信号信号)在 Python 中作为 KeyboardInterrupt 异常可见。你的代码应该能捕捉到它:

#!/usr/bin/env python
from subprocess import call, check_call

try:
   rc = call(['omxplayer', 'first file'])
except KeyboardInterrupt:
   check_call(['omxplayer', 'second file'])
else:
   if rc != 0:
      raise RuntimeError('omxplayer failed to play the first file, '
                         'return code: %d' % rc)

以上假设 omxplayerCtrl+C 退出。

由于多种原因,您可能会看到帮助消息,例如,omxplayer 不支持 --loop 选项(运行 需要手动检查) 您错误地使用了 shell=True 将命令作为列表传递:如果您 需要 ,请始终将命令作为单个字符串传递shell=True 反之:总是(在 POSIX 上)如果 shell=False(默认)将命令作为参数列表传递。