Killing a process created with Python's subpro

2019-01-06 17:40发布

This question already has an answer here:

Here is my thought:

First of all, I created a process by using subprocess.Popen

Second, after certain amount of time, I tried to kill it by Popen.kill()

import subprocess
import os, signal
import time

proc1 = subprocess.Popen("kvm -hda /path/xp.img", shell = True)
time.sleep(2.0)
print 'proc1 = ', proc1.pid
subprocess.Popen.kill(proc1)

However, "proc1" still exists after Popen.kill(). Could any experts tell me how to solve this issue? I appreciate your considerations.

Thanks to the comments from all experts, I did all you recommended, but result still remains the same.

proc1.kill() #it sill cannot kill the proc1

os.kill(proc1.pid, signal.SIGKILL) # either cannot kill the proc1

Thank you all the same.

And I am still waiting for your precious experience on solving this delicate issue.

标签: python popen
4条回答
Animai°情兽
2楼-- · 2019-01-06 18:03

In your code it should be

proc1.kill()

Both kill or terminate are methods of the Popen object which sends the signal signal.SIGKILL to the process.

查看更多
Bombasti
3楼-- · 2019-01-06 18:05

process.terminate() doesn't work when using shell=True. This answer will help you.

查看更多
Rolldiameter
4楼-- · 2019-01-06 18:08

Only use Popen kill method

      process = subprocess.Popen(task.getExecutable(), stdout=subprocess.PIPE,      stderr=subprocess.PIPE, shell=True)
      process.kill()
查看更多
【Aperson】
5楼-- · 2019-01-06 18:24

How about using os.kill? See the docs here: http://docs.python.org/library/os.html#os.kill

查看更多
登录 后发表回答