Sanket
Sanket

Reputation: 745

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'
>>> 

Upvotes: 0

Views: 421

Answers (2)

Yann Vernier
Yann Vernier

Reputation: 15887

First, let's examine what os.popen('ps -ef | grep some_process | wc -l').read() does. It spawns a shell, with the given command line in its argument list. That then spawns a pipeline of three processes, and among those ps collects the list of processes. At this point, at least the first shell and the grep have some_process in their argument list; possibly the third pipeline process too, if it hasn't yet executed wc. grep filters the list, and wc counts the results. Note that the only reason the arguments were even in the listing for grep to find is the use of -f, which might have been redundant since wc doesn't care.

This should make it clear why someone suggested [s]ome_process; this pattern doesn't match itself, and would exclude all of those 2-3 processes, assuming the glob didn't work. It needs quotes to work should there happen to exist a file named some_process.

There may be far more reliable methods, however. We're already running a Python process, so we can easily count things, and ps has switches to select specific processes, for instance ps -C some_process to select on command name. Thus a more discriminate form of the task might be:

subprocess.check_output(["ps", "--no-heading", "-C", "python"]).count(b'\n')

Check for other relevant switches to command such as ps using man.

Upvotes: 1

Sunitha
Sunitha

Reputation: 12015

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

Upvotes: 1

Related Questions