0

I've created a very large and complex python program and I now know it has a serious bug that I'm having a very hard time pinning down. I'm using this code in a production environment so I need a stop-gap measure to implement until I find and correct my coding issue. I need to create a bash script that I can use to check for CPU usage of my python program and kill it if it's consistently below x%. Once killed it will automatically restart on it's own.

I'm using the following to get my PID and %CPU

$ ps -eo pid -eo pcpu -eo command |grep python |grep pycode.py

2940 71.9 python pycode.py

How can I check %cpu, which is 71.9 above, against x% cpu and then kill the PID if needed.

Also, the python program does not go runaway nor does it die. It simply drops to below 5% cpu and stays there and the UI freezes. I'm new to bash so I really don't know where to start.

2

Here's a crude attempt:

read -r pid cpu rest < <(ps -eo pid -eo pcpu -eo command |grep python |grep pycode.py)
if (( ${cpu%.*} < 5 )) ; then
    kill -TERM $pid
fi

We use ${cpu%.*} to truncate it to an integer, since bash can't handle floats. This only runs once; if you want to keep it going, put it on a cron job, or put it in a loop with sleep 5 or whatever.

  • I get an error when running the above: line 2: ((: < 5 : syntax error: operand expected (error token is "< 5 ") – user72055 Sep 15 '15 at 17:11
  • What's the value of $cpu when you do that? If you ran it from the shell, it should still be in the environment, or you could add echo $cpu right before the if statement. The obvious issue would be if $cpu was empty, as would be the case if pycode.py was not running when the code was run. – Tom Hunt Sep 15 '15 at 17:17
  • I found it. Thank you. It works and I understand it, so I can make changes as needed. – user72055 Sep 15 '15 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.