简体   繁体   中英

Python - psutil Windows permission error?

I'm attempting to get the PID of a process on Windows 7 using psutil, but I'm running into a permissions error. I've tried running the Command Prompt which is running the script as administrator, but this doesn't seem to have any effect. Both the error and the relevant code is below. The line that the error occurs on is when trying to access the process name using proc.name . Any suggestions on how I might fix this? Thank you much!

Error:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\psutil\_psmswindows.py", line 190, in wrapper
    return fun(self, *args, **kwargs)
  File "C:\Python33\lib\site-packages\psutil\_psmswindows.py", line 229, in get_process_exe
    return _convert_raw_path(_psutil_mswindows.get_process_exe(self.pid))
PermissionError: [WinError 5] Access is denied

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "simple_address_retrieve.py", line 14, in <module>
    if proc.name == PROCNAME:
  File "C:\Python33\lib\site-packages\psutil\_common.py", line 48, in __get__
    ret = self.func(instance)
  File "C:\Python33\lib\site-packages\psutil\__init__.py", line 341, in name
    name = self._platform_impl.get_process_name()
  File "C:\Python33\lib\site-packages\psutil\_psmswindows.py", line 190, in wrapper
    return fun(self, *args, **kwargs)
  File "C:\Python33\lib\site-packages\psutil\_psmswindows.py", line 222, in get_process_name
    return os.path.basename(self.get_process_exe())
  File "C:\Python33\lib\site-packages\psutil\_psmswindows.py", line 194, in wrapper
    raise AccessDenied(self.pid, self._process_name)
psutil._error.AccessDenied: (pid=128)

Code:

PROCNAME = "MyProcessName.exe"

for proc in psutil.process_iter():
    if proc.name == PROCNAME:
        print(proc)

get_process_list() is deprecated use psutil.process_iter() 0.6.0 . Also in newest psutil this problem seems to be fixed. You can also continue iterating over processes:

for proc in psutil.process_iter():
   try:
       if proc.name == PROCNAME:
          print(proc)
   except (PermissionError, AccessDenied):
       print "Permission error or access denied on process" # can't display name or id here

From comments:

...and searching more, it appears that this is an issue that the author won't fix (too complex): http://groups.google.com/forum/#!topic/psutil/EbdkIGlb4ls . This answer looks like the best way to do this. There is no PermissionError though, so just catch AccessDenied

except psutil.AccessDenied: # windows

Example

def test_children_duplicates(self):
        # find the process which has the highest number of children
        table = collections.defaultdict(int)
        for p in psutil.process_iter():
            try:
                table[p.ppid()] += 1
            except psutil.Error:
                pass
        # this is the one, now let's make sure there are no duplicates
        pid = sorted(table.items(), key=lambda x: x[1])[-1][0]
        p = psutil.Process(pid)
        try:
            c = p.children(recursive=True)
        except psutil.AccessDenied:  # windows
            pass
        else:
            self.assertEqual(len(c), len(set(c))) 

Ref: https://www.programcreek.com/python/example/53869/psutil.process_iter

def find_process(regex):
    "If 'regex' match on cmdline return number and list of processes with his pid, name, cmdline."
    process_cmd_name = re.compile(regex)
    ls = []
    for proc in psutil.process_iter(attrs=['pid','name','cmdline']):
        try:
            if process_cmd_name.search(str(" ".join(proc.cmdline()))):
                ls.append(proc.info)
        except psutil.AccessDenied:  # windows
            pass
    return (ls)

There is possible usage in list comprehensions in conjuction of psutil.AccessDenied ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM