Question

Given a pexpect spawned process that's opened with sudo, like so:

#!/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

How would I kill this process on fail (or success, for that matter)?

I've tried the following (replacing # insert code here):

child.kill(0)
child.close(force=True)

Both give the following error, which makes sense as the Python script is not a root process, and it's trying to kill something that is a root process.

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.

It is not possible to run the script as root, due to file permissions (run from a shared NFS drive where root access is blocked)

Was it helpful?

Solution

Use sudo to kill it as root:

subprocess.call(['sudo', 'kill', str(child.pid)])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top