Search code examples
pythonlinuxpopenpython-os

Python os.popen() returns running process count incremented by 1


I have tried to get process count by using ps, when I execute command on my linux terminal it returns correct count. But when I am executing same command in python shell using os.popen(), then the returned count is always incremented by one

root@dev:/home/admin# ps -ef | grep some_process | wc -l
1
root@dev:/home/admin# python
Python 2.7.6 (default, Nov 23 2017, 15:49:48) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.popen('ps -ef | grep some_process | wc -l').read()
'2\n'
>>> 

Solution

  • os.popen would have launched the process /bin/sh -c 'ps -ef | grep some_precess | wc -l' which will also be counted as a process matching your condition.

    Instead try the cmd ps -ef | grep some_process | grep -v grep | wc -l both from shell and python, so that you be accidentally counting this launched process