In python, how can I run a command line program that does not return until I send it Ctrl + D

I am writing python unit tests that test the REST API, which should work like another process.

A REST server is a tomcat application that I call from the shell to run in development mode, so what I want to do in a python test:

  • Start the server, return when the server is up.
  • Running unit tests
  • Send the server Ctrl+Dto shut down gracefully.

Is there a way to use one input point for python so that the server starts up and unit tests run all from a single python script call?

I am looking at the python subprocess and multithreading in python, but I still don't quite understand how to get there.

For acquaintances, this is the Atlassian JIRA plugin that we are developing, therefore the actual shell command is "atlas-run".

+4
source share
1 answer

Since no one has suggested any code to solve this problem, I would do something like the following. It turns out to be pexpectvery powerful, and you do not need a module signal.

import os
import sys
import pexpect

def run_server():
    server_dir = '/path/to/server/root'
    current_dir = os.path.abspath(os.curdir)

    os.chdir(server_dir)
    server_call = pexpect.spawn('atlas-run')
    server_response = server_call.expect(['Server Error!', 'Sever is running!'])
    os.chdir(current_dir)
    if server_response:
        return server_call #return server spawn object so we can shutdown later
    else:
        print 'Error starting the server: %s'%server_response.after
        sys.exit(1)

def run_unittests():
    # several ways to do this. either make a unittest.TestSuite or run command line
    # here is the second option
    unittest_dir = '/path/to/tests'
    pexpect.spawn('python -m unittest discover -s %s -p "*test.py"'%unittest_dir)
    test_response = pexpect.expect('Ran [0-9]+ tests in [0-9\.]+s') #catch end
    print test_response.before #print output of unittests before ending.
    return

def main():
    server = run_sever()
    run_unittests()
    server.sendcontrol('d') #shutdown server

if __name__ == "__main__":
    main()
+3
source

All Articles