鉴于使用sudo打开的pexpect衍生进程,如下所示:
#!/usr/bin/env python
import pexpect
cmd = ['sudo', 'bash', '-c', '"some long-running sudo command"']
cmd = ' '.join(cmd)
child = pexpect.spawn(cmd, timeout=60)
i = child.expect([
'success',
'error'])
if i == 0:
print('ok')
else:
print('fail')
# insert code here
如何在失败时取消此过程(或成功,就此而言)?
我尝试了以下内容(替换# insert code here
):
child.kill(0)
child.close(force=True)
两者都给出了以下错误,这是有道理的,因为 Python脚本不是根进程,它正在尝试杀死一些根进程。
Traceback (most recent call last):
File "./myscript.py", line 85, in <module>
requires_qemu()
File "./myscript.py", line 82, in requires_qemu
child.close(0)
File "/usr/lib/python2.7/site-packages/pexpect/__init__.py", line 747, in close
raise ExceptionPexpect('Could not terminate the child.')
pexpect.ExceptionPexpect: Could not terminate the child.
由于文件权限(从阻止root访问权限的共享NFS驱动器运行),无法以root用户身份运行脚本。
答案 0 :(得分:6)
使用sudo
以root身份杀死它:
subprocess.call(['sudo', 'kill', str(child.pid)])