如何中断sh启动的子进程?

2024-05-19 21:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

示例:等待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

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


Tags: inevent示例for进程sh事件流程
2条回答

也许您最好直接使用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)

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

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

相关问题 更多 >