# Buggy code
def _init(self, pid, _ignore_nsp=False):
    if pid is None:
        pid = os.getpid()
    else:
        if not _PY3 and not isinstance(pid, (int, long)):
            raise TypeError("pid must be an integer (got %r)" % pid)
        if pid < 0:
            raise ValueError("pid must be a positive integer (got %s)" % pid)
    self._pid = pid
    self._name = None
    self._exe = None
    self._create_time = None
    self._gone = False
    self._hash = None
    # used for caching on Windows only (on POSIX ppid may change)
    self._ppid = None
    # platform-specific modules define an _psplatform.Process
    # implementation class
    self._proc = _psplatform.Process(pid)
    self._last_sys_cpu_times = None
    self._last_proc_cpu_times = None
    # cache creation time for later use in is_running() method
    try:
        self.create_time()
    except AccessDenied:
        # we should never get here as AFAIK we're able to get
        # process creation time on all platforms even as a
        # limited user
        pass
    except NoSuchProcess:
        if not _ignore_nsp:
            msg = "no process found with pid %s" % pid
            raise NoSuchProcess(pid, None, msg)
        else:
            self._gone = True
    # This pair is supposed to indentify a Process instance
    # univocally over time (the PID alone is not enough as
    # it might refer to a process whose PID has been reused).
    # This will be used later in __eq__() and is_running().
    self._ident = (self.pid, self._create_time)


# Traceback (psutil._error.NoSuchProcess)
How to reproduce:

1. start Photoshop CS6 on a Mountain Lion OSX
2. import psutil; [x.as_dict() for x in psutil.process_iter()] # (in .py file, ipython)



What is the expected output?
A long list of processes and related information



What do you see instead?


$ python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
[x.as_dict() for x in psutil.process_iter() if x.is_running()]
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.py",
line 225, in as_dict
ret = attr()
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.py",
line 414, in get_nice
return self._platform_impl.get_process_nice()
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/_psosx.py",
line 151, in wrapper
raise NoSuchProcess(self.pid, self._process_name)
psutil._error.NoSuchProcess: process no longer exists (pid=46244)

or within iPython notebook:
[x.as_dict() for x in psutil.process_iter() if x.is_running()]
---------------------------------------------------------------------------
NoSuchProcess                             Traceback (most recent call last)
<ipython-input-108-a71c6dffe397> in <module>()
----> 1 [x.as_dict() for x in psutil.process_iter() if x.is_running()]

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.pyc
in as_dict(self, attrs, ad_value)
223                         ret = attr(interval=0)
224                     else:
--> 225                         ret = attr()
226                 else:
227                     ret = attr

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.pyc
in get_nice(self)
412     def get_nice(self):
413         """Get process niceness (priority)."""
--> 414         return self._platform_impl.get_process_nice()
415
416     @_assert_pid_not_reused

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/_psosx.pyc in
wrapper(self, *args, **kwargs)
149             err = sys.exc_info()[1]
150             if err.errno == errno.ESRCH:
--> 151                 raise NoSuchProcess(self.pid, self._process_name)
152             if err.errno in (errno.EPERM, errno.EACCES):
153                 raise AccessDenied(self.pid, self._process_name)

NoSuchProcess: process no longer exists (pid=46243, name='adobe_licutil')

When I close Photoshop, the error will not show up. When starting it again the
error reappears.
An additional is_running() check within the list comprehension does not change
a thing and running the code several times will not change the reported pid.

# Fixed code
def _init(self, pid, _ignore_nsp=False):
    if pid is None:
        pid = os.getpid()
    else:
        if not _PY3 and not isinstance(pid, (int, long)):
            raise TypeError("pid must be an integer (got %r)" % pid)
        if pid < 0:
            raise ValueError("pid must be a positive integer (got %s)" % pid)
    self._pid = pid
    self._name = None
    self._exe = None
    self._create_time = None
    self._gone = False
    self._hash = None
    # used for caching on Windows only (on POSIX ppid may change)
    self._ppid = None
    # platform-specific modules define an _psplatform.Process
    # implementation class
    self._proc = _psplatform.Process(pid)
    self._last_sys_cpu_times = None
    self._last_proc_cpu_times = None
    # cache creation time for later use in is_running() method
    try:
        self.create_time()
    except AccessDenied:
        # we should never get here as AFAIK we're able to get
        # process creation time on all platforms even as a
        # limited user
        pass
    except ZombieProcess:
        # Let's consider a zombie process as legitimate as
        # tehcnically it's still alive (it can be queried,
        # although not always, and it's returned by pids()).
        pass
    except NoSuchProcess:
        if not _ignore_nsp:
            msg = "no process found with pid %s" % pid
            raise NoSuchProcess(pid, None, msg)
        else:
            self._gone = True
    # This pair is supposed to indentify a Process instance
    # univocally over time (the PID alone is not enough as
    # it might refer to a process whose PID has been reused).
    # This will be used later in __eq__() and is_running().
    self._ident = (self.pid, self._create_time)