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 exec
uted 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
.