Is there a way to monitor the amount of processing power used in a program in Python? My goal is to kill a program if someone is using too much power while connecting to my server in case of malicious intent.
Asked
Active
Viewed 1,449 times
1
-
You want your Python program to monitor its own CPU use? Or you want to monitor the CPU use of other programs? – abarnert Aug 13 '13 at 20:37
-
3Are you sure that's what you want? It won't stop something like, say, a [fork bomb](https://en.wikipedia.org/wiki/Fork_bomb). How are you going to decide whether something is malicious or just the most CPU-intensive thing on the machine at the moment? – user2357112 Aug 13 '13 at 20:38
-
3Also, almost every system has built-in ways to restrict processes. On Windows these are pretty complicated (and often hidden on non-Server releases, and different from version to version); on most *nix systems it can be as simple as calling `ulimit` from the shell before launching the Python interpreter. – abarnert Aug 13 '13 at 20:39
-
This is a related thread: http://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python – Jay B. Martin Aug 13 '13 at 20:39
3 Answers
4
Even if psutil provides OS-level information in a relatively OS-independent way, sometimes it is better indicated to interact directly with the local OS. Doing so at the API level can be seen as too complex and difficult to debug. If this is the case, some useful alternatives in the case of Windows are:
wmic process list full
and
wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime
That's the closest Windows equivalent to *nix's better known ps
.
The suggestion is, then, to "Popen" them, and pipe their output back for analysis. My understanding is that at least the first (wmic process
) supports continuous mode.

Mario Rossi
- 7,651
- 27
- 37