crontab to run python file if not running already
<p>I want to execute my python file via crontab only if its down or not running already. I tried adding below entry in cron tab but it does not work</p>

<pre><code>24 07 * * * pgrep -f test.py || nohup python /home/dp/script/test.py &amp; &gt; /var/tmp/test.out
</code></pre>

<p>test.py works fine if i run  <code>pgrep -f test.py || nohup python /home/dp/script/test.py &amp; &gt; /var/tmp/test.out</code> manually and it also works in crontab if i remove pgrep -f test.py || from my crontab and just keep <code>24 07 * * * nohup python /home/dp/script/test.py &amp; &gt; /var/tmp/test.out</code></p>

<p>Any idea why crontab does not work if i add pgrep -f? is there any other way i can run test.py just one time to avoid multiple running processes of test.py?
Thanks,
Deepak</p>

<h3>pgrep -f lists itself as a false match when run from cron</h3>

<p>I did the test with a <code>script.py</code> running an infinite loop. Then</p>

<pre class="lang-sh prettyprint-override"><code>pgrep -f script.py
</code></pre>

<p>...from the terminal, gave <strong><em>one</em></strong> pid, <code>13132</code> , while running from cron:</p>

<pre class="lang-sh prettyprint-override"><code>pgrep -f script.py &gt; /path/to/out.txt
</code></pre>

<p>outputs <strong><em>two</em></strong> pids, <code>13132</code> and <code>13635</code>.</p>

<p>We can therefore conclude that the command <code>pgrep -f script.py</code> lists itself as a match, when run from cron. Not sure how and why, but most likely, this is indirectly caused by the fact that <code>cron</code> runs with a quite limited set of environment variables (HOME, LOGNAME, and SHELL).</p>

<h3>The solution</h3>

<p>Running <code>pgrep -f</code> from a (wrapper) script makes the command <em>not</em> list itself, even when run from <code>cron</code>. Subsequently, run the wrapper from <code>cron</code>:</p>

<pre class="lang-sh prettyprint-override"><code>#!/bin/bash

if ! pgrep -f 'test.py'
then
    nohup python /home/dp/script/test.py &amp; &gt; /var/tmp/test.out
# run the test, remove the two lines below afterwards
else
    echo "running" &gt; ~/out_test.txt
fi
</code></pre>

python crontab