Run background job in fabric

After building the server, I wanted to start and stop the application for confirmation, cut out the log at that time and collect it, but I got stuck a little, so make a note.

Since a pseudo terminal is created every time run () is called, the process ends when run () is exited by simply executing it in the background by a method such as "[command] &". It ends up. When I ran it as a daemon with "nohup" or "disdown" and set pty = False so that fabric run () did not create a pseudo terminal, it worked as expected.

Below is a sample.

#Run
fab test_tail_logfile -H localhost -u xxxxx -p xxxxx --port 2222

fabfile.py


from fabric.api import run, get, quiet


def kill_background_job(command):
    with quiet():
        run(u"pkill -f '%s'" % command)


def background_run(command, stdout):
    run(u"nohup %s > %s 2>&1 &" % (command, stdout), pty=False)


def test_tail_logfile():
    '''
Execute other processing while tailing the log in the background,
Sample to stop tail and collect logs after processing
    '''
    #Create a log file for testing
    run(u"echo '**********************' > work.log")

    #Log tail start
    background_run(u"tail -f work.log", u"out.log")

    #Try to write something in the log
    run("echo 'piyo piyo' >> work.log")
    run("echo 'hoge' >> work.log")

    #Stop tail
    kill_background_job(u"tail -f work.log")

    #Check if you can log
    run(u"cat %s" % u"out.log")
    #Collect logs
    get(r"out.log", u".\\log\\out.log")

Recommended Posts

Run background job in fabric
Run the task in the background on the sshed server
Dynamically set env.hosts in fabric
Run automatic jobs in python
Run shell commands in python
Run Python unittests in parallel
Run Amazon Linux 2 in VirtualBox
Run a multi-line script in a PDB
Run eclipse in Docker environment (noVNC)
Let's run "python -m antigravity" in python
Run shell command / python in R
Run unittests in Python (for beginners)
How to run TensorFlow 1.0 code in 2.0
Run a simple algorithm in Python
[Linux] Who is the background job! ??