How to monitor a python process and restart it upon abnormal termination
<p>Assume that there is a <code>task.py</code>,breaking due to memory overflow.How can i monitor this and restart it?</p>

<pre><code>import time
while(1):
    print('.')
    # simulate breaks
    time.sleep(2)
    exit(0)
</code></pre>

<p>Thanks</p>

<p>Something like this should work:</p>

<pre><code>while ! /path/to/task.py; do
    echo 'restarting task...'
done
</code></pre>

<p>If <em>task.py</em> exits with non-zero exit status the loop will continue and run the script again. The loop will only break when <em>task.py</em> exits with <code>0</code>.</p>

<p>If your program is errored and yield to non-zero exit at all time, this will end up being an infinite loop. So it's better to restrict the number of restart tries by a max_try value:</p>

<pre><code>#!/bin/bash
max_try=100
count=1
while ! python /path/to/task.py; do
    ((count++)) # increment (Bashism)
    #count=$(expr $count + 1) # increment (portable)
    if [ $count -gt $max_try ]; then break; fi
    echo 'restarting task...'
done
</code></pre>

python linux bash