0

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

示例:等待 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' 终止了进程,但我无法捕捉到异常:

未处理的异常

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

4

2 回答 2

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)
于 2013-09-19T08:28:41.070 回答
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
于 2013-09-20T04:10:13.913 回答