Is it possible for app.py to launch server.py in the background so that server.py stays running after app.py terminates?

I have a regression test application, regression.py. But some of the tests depend on test_server.py being up and running.

At the moment I do this in regression.py’s main():

    check_server()
...
def check_server():
    reply = subprocess.run(['nc', '-vz', 'localhost', '5558'],
                           stdout=subprocess.DEVNULL,
                           stderr=subprocess.DEVNULL)
    if reply.returncode != 0:
        raise SystemExit('run: ./misc/test_server.py &')

However, I would far rather that check_server() actually started the server. Of course, this is easy to do using subprocess.run() or os.system(); but in both cases the server is shutdown when regression.py finishes. I don’t want it to shutdown because I have other tests that also depend on the server.

So what I want is for each test to check .py to check if the server is running and if not, to start it once and for all, so that for all subsequent tests the server is running.

This stackoverflow answer seems relevant:

The child process receives the same SIGINT as your parent process because it’s in the same process group. You can put the child in its own process group by calling os.setpgrp() in the child process. Popen’s preexec_fn argument is useful here:

subprocess.Popen(['nohup', 'my_command'],
                stdout=open('/dev/null', 'w'),
                stderr=open('logfile.log', 'a'),
                preexec_fn=os.setpgrp
                )

(preexec_fn is for un*x-oids only. There appears to be a rough equivalent for Windows “creationflags=CREATE_NEW_PROCESS_GROUP”, but I’ve never tried it.)

That didn’t work, but a slight variation did:

        subprocess.Popen(['nohup', './test_server.py'],
                         cwd=path, stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL,
                         preexec_fn=os.setpgrp).pid

Without the .pid it always failed; but with it, it works.

Thanks!

1 Like