javapythonsubprocessgrizzly

run java server from python and wait until it is up


So I run java server from terminal calling it with:

java =Xmx12G - jar jar.jar --build ../foo --inMemory

then it takes some time for the server to step up, sometimes a minute sometime more.

I want to wait until it is up.

I used subprocess.call() but then it does not terminate, so it waits forever. How can I wait until there is an output:

16:53:28.315 INFO (GrizzlyServer.java:153) Grizzly server running.


Solution

  • There are 2 problems:

    1.) subprocess.call() waits until the java server exits.
    2.) When the parent (Python) process stops usually the child process gets killed.

    In case you still need to make it via Python script, you could run the java server in a separate process group, so it's decoupled from the parent (Python process) - that just works on *nix OSes:

    import os
    import time
    import subprocess
    
    p = subprocess.Popen(
        ['nohup', 'java', '=Xmx12G', '-jar', 'jar.jar', '--build', '../foo', '--inMemory']
        stdout=open('/tmp/logOut.log', 'w'),
        stderr=open('/tmp/logErr.log', 'w'),
        preexec_fn=os.setpgrp
    )
    
    while True:
        if 'Grizzly server running' in open('/tmp/logOut.log').read():
            break
        time.sleep(1)
    

    Note: You need to pipe into files and read them in Python, if you would pipe into the Python script and the script exits the child process gets killed (no matter if the processes are decoupled)