gadhvi
gadhvi

Reputation: 97

How to get total running process count and thread count in Linux using Python?

I am able to get total process count using terminal commands. I have tried following command for process count-

ps aux | wc -l

And for thread count -

ps -eo nlwp | tail -n +2 | awk '{ num_threads += $1 } END " "{ print num_threads }'

But I don't want to use terminal command as its not allowed in my current project, is there any API or other method where I can get this information without invoking terminal.

I had tried using threading package but its showing at process level, I am getting output as 1.

I tried psutil but it gives info for individual process.

Additional info

OS - Ubuntu 16
Python 3.7.2

Upvotes: 1

Views: 4180

Answers (1)

Maheshwar Kuchana
Maheshwar Kuchana

Reputation: 92

Just try this:

If you're going to do this all with a big shell command, just add the -c argument to grep, so it gives you a count of lines instead of the actual lines:

ps uaxw |grep python |grep -v grep

Of course you could make this more complicated by adding a | wc -l to the end, or by counting the lines in Python, but why?

Alternatively, why even involve the shell? You can search within Python just as easily as you can run grep—and then you don't have the problem that you've accidentally created a grep process that ps will repeat as matching your search and then need to grep -v it back out:

procs = subprocess.check_output(['ps', 'uaxw']).splitlines()
kms_procs = [proc for proc in procs if 'kms' in proc]
count = len(kms_procs)

Or, even more simply, don't ask ps to give you a whole bunch of information that you don't want and then figure out how to ignore it, just ask for the information you want:

procs = subprocess.check_output(['ps', '-a', '-c', '-ocomm=']).splitlines()
count = procs.count('kms')

Or, even more more simplierly, install psutil and don't even try to run subprocesses and parse their output:

count = sum(1 for proc in psutil.process_iter() if proc.name() == 'kms')

Upvotes: 2

Related Questions