如何中断sh发起的子进程?

时间:2013-09-19 05:37:56

标签: python subprocess

我想处理子进程的输出,并在收到足够的输出后决定终止该子进程。我的程序逻辑决定我们何时有足够的输入。

示例:等待Udev事件

try:
  for event in sh.udevadm('monitor', _iter=True):
    if event matches usb stick added:
      print("Ok, I will work with that USB stick you just plugged in!")
      break
except:
  pass

print("I copy stuff on your USB stick now!")

'break'终止进程,但我无法捕获异常:

Unhandled exception

终止子流程的正确方法是什么?如何处理异常?

2 个答案:

答案 0 :(得分:1)

也许您最好直接使用subprocess.Popen代替sh库。

类似于:

$ cat udevtest.py
import subprocess

try:
    proc = subprocess.Popen(["udevadm", "monitor"], stdout=subprocess.PIPE, 
                                                    stderr=subprocess.STDOUT)
    while True:
        line = proc.stdout.readline()
        if line == "" or len(line) == 0:
            break  # EOF

        if line.find("pci0000") != -1:  # your trigger
            print("TRIGGER %s" % line.strip())
            break

    proc.terminate()
    proc.wait()
except Exception, e:
    print(e)

答案 1 :(得分:0)

找到了一种使用交互式回调的方式。

http://amoffat.github.io/sh/#interactive-callbacks

我觉得非常整洁。

def wait_for_plugged_in_drive(self):
    print("Plugin an external HDD or USB stick.")

    sh.udevadm.monitor(_out=self._scan_and_terminate).wait()

def _scan_and_terminate(self, line, stdin, process):

    match = re.search('add\\s+/.*/block/sd./(sd..)', line)

    if match is not None:

        self.device = '/dev/' + match.group(1)
        print("USB stick recognized {0}".format(self.device))

        process.terminate()
        return True