How to find Tomcat's PID and kill it in python?

Posted by 4herpsand7derpsago on Stack Overflow See other posts from Stack Overflow or by 4herpsand7derpsago
Published on 2012-10-02T02:23:11Z Indexed on 2012/10/02 3:37 UTC
Read the original article Hit count: 255

Filed under:
|
|
|
|

Normally, one shuts down Apache Tomcat by running its shutdown.sh script (or batch file). In some cases, such as when Tomcat's web container is hosting a web app that does some crazy things with multi-threading, running shutdown.sh gracefully shuts down some parts of Tomcat (as I can see more available memory returning to the system), but the Tomcat process keeps running.

I'm trying to write a simple Python script that:

  1. Calls shutdown.sh
  2. Runs ps -aef | grep tomcat to find any process with Tomcat referenced
  3. If applicable, kills the process with kill -9 <PID>

Here's what I've got so far (as a prototype - I'm brand new to Python BTW):

#!/usr/bin/python

# Imports
import sys
import subprocess

# Load from imported module.
if __init__ == "__main__":
    main()

# Main entry point.
def main():
    # Shutdown Tomcat
    shutdownCmd = "sh ${TOMCAT_HOME}/bin/shutdown.sh"
    subprocess.call([shutdownCmd], shell=true)

    # Check for PID
    grepCmd = "ps -aef | grep tomcat"
    grepResults = subprocess.call([grepCmd], shell=true)

    if(grepResult.length > 1):
        # Get PID and kill it.
        pid = ???
        killPidCmd = "kill -9 $pid"
        subprocess.call([killPidCmd], shell=true)

    # Exit.
    sys.exit()

I'm struggling with the middle part - with obtaining the grep results, checking to see if their size is greater than 1 (since grep always returns a reference to itself, at least 1 result will always be returned, methinks), and then parsing that returned PID and passing it into the killPidCmd. Thanks in advance!

© Stack Overflow or respective owner

Related posts about python

Related posts about tomcat