utils.py 1.14 KB
Newer Older
1
2
3
# Copyright (c) 2020, CNRS
# Authors: Guilhem Saurel <guilhem.saurel@laas.fr>

4
import os
5
6
7
import subprocess
import time

8
9
10
11
12
13
14
15
try:
    from subprocess import DEVNULL, run
except ImportError:  # Python2 fallback
    DEVNULL = os.open(os.devnull, os.O_RDWR)

    def run(*args):
        subprocess.Popen(*args).wait()

16
17
18
19
20

class ServerManager:
    """A context to ensure a server is running."""
    def __init__(self, server):
        self.server = server
21
        run(['killall', self.server])
22
23

    def __enter__(self):
24
25
26
27
28
29
30
        """Run the server in background

        stdout and stderr outputs of the child process are redirected to devnull (hidden).
        preexec_fn is used to ignore ctrl-c signal send to the main script
        (otherwise they are forwarded to the child process)
        """
        self.process = subprocess.Popen(self.server,
31
32
                                        stdout=DEVNULL,
                                        stderr=DEVNULL,
33
                                        preexec_fn=os.setpgrp)
34
35
36
37
38
        # give it some time to start
        time.sleep(3)

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.process.kill()