开发者

How to stop a subprocess? (Python)

I have tried both terminate() and kill() but both have failed to stop a subprocess I start in my python code.

Is there any other way?

On Windows with Python 2.7

I have also tried the following with no results...

os.kill(p.pid, signal.SIGTERM)

and

import ctypes
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, theprocess.pid)
ctypes.windll.kernel32.TerminateProcess(handle, 开发者_开发问答-1)
ctypes.windll.kernel32.CloseHandle(handle)


You could use the os.system('taskkill') here:http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/taskkill.mspx?mfr=true


Try using psutil, or another way to remotely kill the process itself (psutil is cross platform so the code is nicer):

p = psutil.Process(pid)
p.terminate()  #or p.kill()

Code taken from How to terminate process from Python using pid?.

Note that if using shell=True, the PID is of the shell and not any process it spawned. To kill a subprocess with shell=True you may look at How to terminate a python subprocess launched with shell=True

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜