1

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.

4
  • You want your Python program to monitor its own CPU use? Or you want to monitor the CPU use of other programs? Commented Aug 13, 2013 at 20:37
  • 3
    Are you sure that's what you want? It won't stop something like, say, a 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? Commented Aug 13, 2013 at 20:38
  • 3
    Also, 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. Commented Aug 13, 2013 at 20:39
  • This is a related thread: stackoverflow.com/questions/276052/… Commented Aug 13, 2013 at 20:39

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

psutil

>>> for x in range(3):
...     psutil.cpu_percent(interval=1, percpu=True)
... 
[4.0, 6.9]
[7.0, 8.5]
[1.2, 9.0]

Comments

0

psutil is extremely handy to monitor processes and cpu usage.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.