The simplest answer in my opinion (albiet maybe not ideal), would be to change your
ps -ef | grep <pid>
To:
ps -ef | grep <pid> | grep -v grep
This will ignore the process listing for the grep search containing the PID of the process you are trying to find.
It seems user9876's answer is far more "pythonic" however.