Skip to content
Advertisement

How do I kill a Python script in Java?

I am launching a Python script in Java using Runtime.getRuntime().exec("python myWebService.py") and I am not doing anything else with it in Java. However, now I need to terminate the process from within my Java application. I’ve tried issuing a pkill command from the terminal, outside of the application, and this will not kill the script. Finding the pid in the terminal and then executing a kill pid does work from the terminal, but I have not found a way to get the pid of the process I started in Java. Any ideas?

Advertisement

Answer

The Runtime.getRuntime().exec("python myWebService.py") call returns a process, that has a destroy() method to kill it. You can use that:

Process process = Runtime.getRuntime().exec("python myWebService.py")
process.destroy()
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement