简体   繁体   English

如何检查进程是否在python中运行(在Linux中)?

[英]How to check process have running in python (in linux)?

I am trying to check if the process is running based on process name (test.py) , then exit 我正在尝试根据进程名称(test.py)检查进程是否正在运行,然后退出

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 , 进程未运行,我想检查进程(test.py)是否正在运行,然后退出,但它始终打印进程正在运行,

How do I check the process have running ? 如何检查进程是否已运行? Any suggestions? 有什么建议么? Thanks for any help. 谢谢你的帮助。

The program runs fine for me. 该程序对我来说运行良好。 I guess you are running the program with python instead of python2.7 specifically. 我猜您正在使用python而不是python2.7运行该程序。

(a) Try using python instead of python2.7 in your grep statement,then the culprit is indeed your usage of python. (a)尝试在grep语句中使用python而不是python2.7 ,那么罪魁祸首确实是您对python的使用。

(b) Change it back to python2.7 and run your program with full path to python2.7 (b)将其更改回python2.7并运行具有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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM