# Buggy code
def run(pid):
    ACCESS_DENIED = ""
    try:
        p = psutil.Process(pid)
        pinfo = p.as_dict(ad_value=ACCESS_DENIED)
    except psutil.NoSuchProcess as err:
        sys.exit(str(err))

    try:
        parent = p.parent()
        if parent:
            parent = "(%s)" % parent.name()
        else:
            parent = ""
    except psutil.Error:
        parent = ""
    started = datetime.datetime.fromtimestamp(pinfo["create_time"]).strftime(
        "%Y-%m-%d %H:%M"
    )
    io = pinfo.get("io_counters", ACCESS_DENIED)
    mem = "%s%% (resident=%s, virtual=%s) " % (
        round(pinfo["memory_percent"], 1),
        convert_bytes(pinfo["memory_info"].rss),
        convert_bytes(pinfo["memory_info"].vms),
    )
    children = p.children()

    print_("pid", pinfo["pid"])
    print_("name", pinfo["name"])
    print_("exe", pinfo["exe"])
    print_("parent", "%s %s" % (pinfo["ppid"], parent))
    print_("cmdline", " ".join(pinfo["cmdline"]))
    print_("started", started)
    print_("user", pinfo["username"])
    if POSIX and pinfo["uids"] and pinfo["gids"]:
        print_("uids", "real=%s, effective=%s, saved=%s" % pinfo["uids"])
    if POSIX and pinfo["gids"]:
        print_("gids", "real=%s, effective=%s, saved=%s" % pinfo["gids"])
    if POSIX:
        print_("terminal", pinfo["terminal"] or "")
    if hasattr(p, "getcwd"):
        print_("cwd", pinfo["cwd"])
    print_("memory", mem)
    print_(
        "cpu",
        "%s%% (user=%s, system=%s)"
        % (
            pinfo["cpu_percent"],
            getattr(pinfo["cpu_times"], "user", "?"),
            getattr(pinfo["cpu_times"], "system", "?"),
        ),
    )
    print_("status", pinfo["status"])
    print_("niceness", pinfo["nice"])
    print_("num threads", pinfo["num_threads"])
    if io != ACCESS_DENIED:
        print_(
            "I/O",
            "bytes-read=%s, bytes-written=%s"
            % (convert_bytes(io.read_bytes), convert_bytes(io.write_bytes)),
        )
    if children:
        print_("children", "")
        for child in children:
            print_("", "pid=%s name=%s" % (child.pid, child.name()))

    if pinfo["open_files"] != ACCESS_DENIED:
        print_("open files", "")
        for file in pinfo["open_files"]:
            print_("", "fd=%s %s " % (file.fd, file.path))

    if pinfo["threads"]:
        print_("running threads", "")
        for thread in pinfo["threads"]:
            print_(
                "",
                "id=%s, user-time=%s, sys-time=%s"
                % (thread.id, thread.user_time, thread.system_time),
            )
    if pinfo["connections"] not in (ACCESS_DENIED, []):
        print_("open connections", "")
        for conn in pinfo["connections"]:
            if conn.type == socket.SOCK_STREAM:
                type = "TCP"
            elif conn.type == socket.SOCK_DGRAM:
                type = "UDP"
            else:
                type = "UNIX"
            lip, lport = conn.laddr
            if not conn.raddr:
                rip, rport = "*", "*"
            else:
                rip, rport = conn.raddr
            print_(
                "",
                "%s:%s -> %s:%s type=%s status=%s"
                % (lip, lport, rip, rport, type, conn.status),
            )


# 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 run(pid):
    ACCESS_DENIED = ""
    try:
        p = psutil.Process(pid)
        pinfo = p.as_dict(ad_value=ACCESS_DENIED)
    except psutil.NoSuchProcess as err:
        sys.exit(str(err))

    try:
        parent = p.parent()
        if parent:
            parent = "(%s)" % parent.name()
        else:
            parent = ""
    except psutil.Error:
        parent = ""
    if pinfo["create_time"] != ACCESS_DENIED:
        started = datetime.datetime.fromtimestamp(pinfo["create_time"]).strftime(
            "%Y-%m-%d %H:%M"
        )
    else:
        started = ACCESS_DENIED
    io = pinfo.get("io_counters", ACCESS_DENIED)
    if pinfo["memory_info"] != ACCESS_DENIED:
        mem = "%s%% (resident=%s, virtual=%s) " % (
            round(pinfo["memory_percent"], 1),
            convert_bytes(pinfo["memory_info"].rss),
            convert_bytes(pinfo["memory_info"].vms),
        )
    else:
        mem = ACCESS_DENIED
    children = p.children()

    print_("pid", pinfo["pid"])
    print_("name", pinfo["name"])
    print_("exe", pinfo["exe"])
    print_("parent", "%s %s" % (pinfo["ppid"], parent))
    print_("cmdline", " ".join(pinfo["cmdline"]))
    print_("started", started)
    print_("user", pinfo["username"])
    if POSIX and pinfo["uids"] and pinfo["gids"]:
        print_("uids", "real=%s, effective=%s, saved=%s" % pinfo["uids"])
    if POSIX and pinfo["gids"]:
        print_("gids", "real=%s, effective=%s, saved=%s" % pinfo["gids"])
    if POSIX:
        print_("terminal", pinfo["terminal"] or "")
    if hasattr(p, "getcwd"):
        print_("cwd", pinfo["cwd"])
    print_("memory", mem)
    print_(
        "cpu",
        "%s%% (user=%s, system=%s)"
        % (
            pinfo["cpu_percent"],
            getattr(pinfo["cpu_times"], "user", "?"),
            getattr(pinfo["cpu_times"], "system", "?"),
        ),
    )
    print_("status", pinfo["status"])
    print_("niceness", pinfo["nice"])
    print_("num threads", pinfo["num_threads"])
    if io != ACCESS_DENIED:
        print_(
            "I/O",
            "bytes-read=%s, bytes-written=%s"
            % (convert_bytes(io.read_bytes), convert_bytes(io.write_bytes)),
        )
    if children:
        print_("children", "")
        for child in children:
            print_("", "pid=%s name=%s" % (child.pid, child.name()))

    if pinfo["open_files"] != ACCESS_DENIED:
        print_("open files", "")
        for file in pinfo["open_files"]:
            print_("", "fd=%s %s " % (file.fd, file.path))

    if pinfo["threads"]:
        print_("running threads", "")
        for thread in pinfo["threads"]:
            print_(
                "",
                "id=%s, user-time=%s, sys-time=%s"
                % (thread.id, thread.user_time, thread.system_time),
            )
    if pinfo["connections"] not in (ACCESS_DENIED, []):
        print_("open connections", "")
        for conn in pinfo["connections"]:
            if conn.type == socket.SOCK_STREAM:
                type = "TCP"
            elif conn.type == socket.SOCK_DGRAM:
                type = "UDP"
            else:
                type = "UNIX"
            lip, lport = conn.laddr
            if not conn.raddr:
                rip, rport = "*", "*"
            else:
                rip, rport = conn.raddr
            print_(
                "",
                "%s:%s -> %s:%s type=%s status=%s"
                % (lip, lport, rip, rport, type, conn.status),
            )