psutil is an interesting Python package that provides us with valuable insights about running processes, their memory and CPU usage and many more key aspects for monitoring and profiling processes across all major platforms. Thus, it is an incredibly useful tool for system admins, developers and testers alike. Now one of my favourite methods is
cmdline(). Defined in the package’s
Process class, it yields the whole CLI command of a running process in array form. There is one important catch on Windows though that got me kinda by surprise: While iterating casually through all my processes I suddenly got an AccessDenied error.
What did I try?
For an advanced verification in a process management – related test case I wanted to print the executed CLI command in a log file, so basically this:
import psutil for pc in psutil.process_iter(): print(pc.cmdline())
But that will just throw a painful AccessDenied error at us. Uff.
Why did that happen?
The reason is that
psutil is quite consequent: It really lists every running process. That means even
root processes . That’s okay, it might even be interesting in one case or another, and you can still access selected attributes like the
name() of a root process, if you want. But for me, it doesn’t suffice. I want to see the full-fledged
cmdline(), but I understand that SYSTEM processes are none of my business. Once I came to term with that fact, the solution was easy: We just skip them.
What I did was applying a
try-except around the loop’s inner statement:
import psutil for pc in psutil.process_iter(): try: print(pc.cmdline()) except psutil.AccessDenied: continue
continue statement will make sure that the processes that I’m not supposed to see are happily skipped without hurting the rest of the program flow.
But what if I need to monitor foreign processes?
In that case, we would need to execute the script within the process owner’s user context. That might be a bit fiddly in Windows depending on the use case, but of course that’s still possible. Just remember to keep the try-except block, because there still will be processes you wouldn’t be allowed to see.
Mine, for example. 😄
So far for today. I hope this little Q3A (quick question quick answer) could shed some light upon that surprising AccessDenied error. If you want to learn more about
psutil, I strongly recommend the readthedocs page. Otherwise, if you want to see more quick tips, I have one more for Python here. That one covers Python’s environment variable handling. As an alternative, if you are – like me – into containers, here is a handy
docker ps trick useful for monitoring tasks as well.