我想处理子进程的输出,并在收到足够的输出后决定终止该子进程。我的程序逻辑决定我们何时有足够的输入。
示例:等待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'终止进程,但我无法捕获异常:
终止子流程的正确方法是什么?如何处理异常?
答案 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