0

I am trying to check if the process is running based on process name (test.py) , then exit

l = commands.getstatusoutput("ps aux |grep 'python2.7'| grep      
'test.py' | grep -v 'grep' | wc -l")

if int(l[1]) == 1:
    pid = commands.getstatusoutput("ps -ef |grep 'python2.7'|  grep 'test.py ' |awk '{print $2}'")
    print "the process 'test.py ' have running ,the pid is :"+str(pid[1])
    sys.exit(0)

else:
   print "not running"

Output:

georgetovrea@dev:/test$ python2.7  test.py 
the process 'test.py ' have running ,the pid is :26517
26542

then I try to check

 $ ps aux | grep agg_test
 georgetovrea 25181  0.0  0.0  10944   932 pts/9    S+   23:26   0:00 grep --color=auto test

the process is not running, I want to check if the process( test.py) have running ,then exit , but it's always print the process is running ,

How do I check the process have running ? Any suggestions? Thanks for any help.

georgetovrea
  • 537
  • 1
  • 8
  • 28
  • Is the command you're running from within Python reporting anything different versus if you just run that command in the shell? – Nick T Jun 05 '17 at 16:16
  • Nick, when run the test.py,Output is " the process 'test.py ' have running ,the pid is :26517 26542" – georgetovrea Jun 06 '17 at 00:51
  • Possible duplicate of [this](https://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid-in-python). – IsaacS Mar 06 '18 at 00:19

1 Answers1

-1

The program runs fine for me. I guess you are running the program with python instead of python2.7 specifically.

(a) Try using python instead of python2.7 in your grep statement,then the culprit is indeed your usage of python.

(b) Change it back to python2.7 and run your program with full path to python2.7

The program:

import commands
import sys

l = commands.getstatusoutput("ps aux |grep 'python2.7'| grep 'test.py' | grep -v 'grep' | wc -l")

print(l)
if int(l[1]) == 1:
    pid = commands.getstatusoutput("ps -ef |grep 'python2.7'|  grep 'test.py ' |awk '{print $2}'")
    print "the process 'test.py ' have running ,the pid is :"+str(pid[1])
    sys.exit(0)

else:
   print "not running"

Output:

dhruv@dhruvpathak:/tmp$ /usr/bin/python2.7  test.py 

(0, '1')

the process 'test.py ' have running ,the pid is :15620
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
  • DhruvPathak , I am running the program with python2.7 , the process is not running but running the program to check and get the message "get the process 'test.py' have running ,the pid is :28373 , " – georgetovrea Jun 05 '17 at 06:42
  • What is the name of your python file ? – DhruvPathak Jun 05 '17 at 07:16