gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __truediv__(self, other, **kwargs):
    return EDecimal(Decimal.__truediv__(self, other, **kwargs))


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3.dev227-py2.7.egg/scapy/utils.py", line 67, in __mul__
return EDecimal(Decimal.__mul__(self, other, **kwargs))
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert NotImplemented to Decimal

# Fixed code
def __truediv__(self, other, **kwargs):
    return EDecimal(Decimal.__truediv__(self, Decimal(other), **kwargs))
# Buggy code
def __floordiv__(self, other, **kwargs):
    return EDecimal(Decimal.__floordiv__(self, other, **kwargs))


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3.dev227-py2.7.egg/scapy/utils.py", line 67, in __mul__
return EDecimal(Decimal.__mul__(self, other, **kwargs))
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert NotImplemented to Decimal

# Fixed code
def __floordiv__(self, other, **kwargs):
    return EDecimal(Decimal.__floordiv__(self, Decimal(other), **kwargs))
# Buggy code
def __div__(self, other, **kwargs):
    return EDecimal(Decimal.__div__(self, other, **kwargs))


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3.dev227-py2.7.egg/scapy/utils.py", line 67, in __mul__
return EDecimal(Decimal.__mul__(self, other, **kwargs))
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert NotImplemented to Decimal

# Fixed code
def __div__(self, other, **kwargs):
    return EDecimal(Decimal.__div__(self, Decimal(other), **kwargs))
# Buggy code
def __mod__(self, other, **kwargs):
    return EDecimal(Decimal.__mod__(self, other, **kwargs))


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3.dev227-py2.7.egg/scapy/utils.py", line 67, in __mul__
return EDecimal(Decimal.__mul__(self, other, **kwargs))
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert NotImplemented to Decimal

# Fixed code
def __mod__(self, other, **kwargs):
    return EDecimal(Decimal.__mod__(self, Decimal(other), **kwargs))
# Buggy code
def __divmod__(self, other, **kwargs):
    return EDecimal(Decimal.__divmod__(self, other, **kwargs))


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3.dev227-py2.7.egg/scapy/utils.py", line 67, in __mul__
return EDecimal(Decimal.__mul__(self, other, **kwargs))
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert NotImplemented to Decimal

# Fixed code
def __divmod__(self, other, **kwargs):
    return EDecimal(Decimal.__divmod__(self, Decimal(other), **kwargs))
# Buggy code
def __pow__(self, other, **kwargs):
    return EDecimal(Decimal.__pow__(self, other, **kwargs))


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3.dev227-py2.7.egg/scapy/utils.py", line 67, in __mul__
return EDecimal(Decimal.__mul__(self, other, **kwargs))
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert NotImplemented to Decimal

# Fixed code
def __pow__(self, other, **kwargs):
    return EDecimal(Decimal.__pow__(self, Decimal(other), **kwargs))
# Buggy code
def addfield(self, pkt, s, val):
    len_pkt = self.length_from(pkt)
    return s + struct.pack("%is" % len_pkt, self.i2m(pkt, val))


# Traceback (TypeError)
faucet@faucet:~$ sudo bash
root@faucet:~# python3
Python 3.6.8 (default, Jan 14 2019, 11:02:34)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
from scapy.all import *
scapy.all.send(fuzz(ARP(pdst='127.0.0.1')))
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/scapy/compat.py", line 117, in raw
return bytes(x)
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 441, in __bytes__
return self.build()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 556, in build
p = self.do_build()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 541, in do_build
pay = self.do_build_payload()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 528, in do_build_payload
return self.payload.do_build()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 538, in do_build
pkt = self.self_build()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 519, in self_build
p = f.addfield(self, p, val)
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 134, in addfield
return s + struct.pack(self.fmt, self.i2m(pkt, val))
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 1314, in i2m
f = fld.i2len(pkt, fval)
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 343, in i2len
return self._find_fld_pkt_val(pkt, val).i2len(pkt, val)
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 884, in i2len
return len(i)
TypeError: object of type 'NoneType' has no len()

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/scapy/sendrecv.py", line 314, in send
realtime=realtime, return_packets=return_packets)
File "/usr/local/lib/python3.6/dist-packages/scapy/sendrecv.py", line 287, in __gen_send
s.send(p)
File "/usr/local/lib/python3.6/dist-packages/scapy/arch/linux.py", line 533, in send
sx = raw(ll(x))
File "/usr/local/lib/python3.6/dist-packages/scapy/compat.py", line 119, in raw
return bytes(x, encoding="utf8")
TypeError: encoding without a string argument

# Fixed code
def addfield(self, pkt, s, val):
    len_pkt = self.length_from(pkt)
    if len_pkt is None:
        return s + self.i2m(pkt, val)
    return s + struct.pack("%is" % len_pkt, self.i2m(pkt, val))
# Buggy code
def route(self):
    fld, dst = self.getfield_and_val("pdst")
    fld, dst = fld._find_fld_pkt_val(self, dst)
    if isinstance(dst, Gen):
        dst = next(iter(dst))
    if isinstance(fld, IP6Field):
        return conf.route6.route(dst)
    elif isinstance(fld, IPField):
        return conf.route.route(dst)
    else:
        return None


# Traceback (TypeError)
faucet@faucet:~$ sudo bash
root@faucet:~# python3
Python 3.6.8 (default, Jan 14 2019, 11:02:34)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
from scapy.all import *
scapy.all.send(fuzz(ARP(pdst='127.0.0.1')))
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/scapy/compat.py", line 117, in raw
return bytes(x)
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 441, in __bytes__
return self.build()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 556, in build
p = self.do_build()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 541, in do_build
pay = self.do_build_payload()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 528, in do_build_payload
return self.payload.do_build()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 538, in do_build
pkt = self.self_build()
File "/usr/local/lib/python3.6/dist-packages/scapy/packet.py", line 519, in self_build
p = f.addfield(self, p, val)
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 134, in addfield
return s + struct.pack(self.fmt, self.i2m(pkt, val))
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 1314, in i2m
f = fld.i2len(pkt, fval)
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 343, in i2len
return self._find_fld_pkt_val(pkt, val).i2len(pkt, val)
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 884, in i2len
return len(i)
TypeError: object of type 'NoneType' has no len()

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/scapy/sendrecv.py", line 314, in send
realtime=realtime, return_packets=return_packets)
File "/usr/local/lib/python3.6/dist-packages/scapy/sendrecv.py", line 287, in __gen_send
s.send(p)
File "/usr/local/lib/python3.6/dist-packages/scapy/arch/linux.py", line 533, in send
sx = raw(ll(x))
File "/usr/local/lib/python3.6/dist-packages/scapy/compat.py", line 119, in raw
return bytes(x, encoding="utf8")
TypeError: encoding without a string argument

# Fixed code
def route(self):
    fld, dst = self.getfield_and_val("pdst")
    fld, dst = fld._find_fld_pkt_val(self, dst)
    if isinstance(dst, Gen):
        dst = next(iter(dst))
    if isinstance(fld, IP6Field):
        return conf.route6.route(dst)
    elif isinstance(fld, IPField):
        return conf.route.route(dst)
    else:
        return None, None, None
# Buggy code
def network_stats(self):
    """Return a dictionary containing a summary of the Dot11
    elements fields
    """
    summary = {}
    crypto = set()
    p = self.payload
    while isinstance(p, Dot11Elt):
        if p.ID == 0:
            summary["ssid"] = plain_str(p.info)
        elif p.ID == 3:
            summary["channel"] = ord(p.info)
        elif isinstance(p, Dot11EltRates):
            summary["rates"] = p.rates
        elif isinstance(p, Dot11EltRSN):
            crypto.add("WPA2")
        elif p.ID == 221:
            if isinstance(p, Dot11EltMicrosoftWPA) or p.info.startswith(
                "\x00P\xf2\x01\x01\x00"
            ):
                crypto.add("WPA")
        p = p.payload
    if not crypto:
        if self.cap.privacy:
            crypto.add("WEP")
        else:
            crypto.add("OPN")
    summary["crypto"] = crypto
    return summary


# Traceback (TypeError)
Traceback (most recent call last):
File "min_script.py", line 25, in <module>
sniff(iface="mon0", lfilter=filter_beacon, prn=print_ap)
File "/usr/lib/python3.7/site-packages/scapy/sendrecv.py", line 886, in sniff
r = prn(p)
File "min_script.py", line 12, in print_ap
netstats = p[Dot11Beacon].network_stats()
File "/usr/lib/python3.7/site-packages/scapy/layers/dot11.py", line 430, in network_stats
p.info.startswith('\x00P\xf2\x01\x01\x00'):
TypeError: startswith first arg must be bytes or a tuple of bytes, not str

# Fixed code
def network_stats(self):
    """Return a dictionary containing a summary of the Dot11
    elements fields
    """
    summary = {}
    crypto = set()
    p = self.payload
    while isinstance(p, Dot11Elt):
        if p.ID == 0:
            summary["ssid"] = plain_str(p.info)
        elif p.ID == 3:
            summary["channel"] = ord(p.info)
        elif isinstance(p, Dot11EltRates):
            summary["rates"] = p.rates
        elif isinstance(p, Dot11EltRSN):
            crypto.add("WPA2")
        elif p.ID == 221:
            if isinstance(p, Dot11EltMicrosoftWPA) or p.info.startswith(
                b"\x00P\xf2\x01\x01\x00"
            ):
                crypto.add("WPA")
        p = p.payload
    if not crypto:
        if self.cap.privacy:
            crypto.add("WEP")
        else:
            crypto.add("OPN")
    summary["crypto"] = crypto
    return summary
# Buggy code
def get_ip_from_name(ifname, v6=False):
    """Backward compatibility: indirectly calls get_ips
    Deprecated."""
    return get_ips(v6=v6).get(ifname, "")[0]


# Traceback (IndexError)
from scapy.all import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "scapy\all.py", line 18, in <module>
from scapy.arch import *
File "scapy\arch\__init__.py", line 73, in <module>
from scapy.arch.windows import *  # noqa F403
File "scapy\arch\windows\__init__.py", line 953, in <module>
IFACES.load_from_powershell()
File "scapy\arch\windows\__init__.py", line 843, in load_from_powershell
interface.ip = ifaces_ips.get(interface.name, "")[0]
IndexError: string index out of range

# Fixed code
def get_ip_from_name(ifname, v6=False):
    """Backward compatibility: indirectly calls get_ips
    Deprecated."""
    return get_ips(v6=v6).get(ifname, [""])[0]
# Buggy code
def _exec_query_ps(cmd, fields):
    """Execute a PowerShell query, using the cmd command,
    and select and parse the provided fields.
    """
    if not conf.prog.powershell:
        raise OSError("Scapy could not detect powershell !")
    # Build query
    query_cmd = cmd + [
        "|",
        "select %s" % ", ".join(fields),  # select fields
        "|",
        "fl",  # print as a list
        "|",
        "out-string",
        "-Width",
        "4096",
    ]  # do not crop
    lines = []
    # Ask the powershell manager to process the query
    stdout = POWERSHELL_PROCESS.query(query_cmd)
    # Process stdout
    for line in stdout:
        if not line.strip():  # skip empty lines
            continue
        sl = line.split(":", 1)
        if len(sl) == 1:
            lines[-1] += sl[0].strip()
            continue
        else:
            lines.append(sl[1].strip())
        if len(lines) == len(fields):
            yield lines
            lines = []


# Traceback (IndexError)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "scapy\all.py", line 18, in <module>
from scapy.arch import *
File "scapy\arch\__init__.py", line 73, in <module>
from scapy.arch.windows import *  # noqa F403
File "scapy\arch\windows\__init__.py", line 946, in <module>
IFACES.load_from_powershell()
File "scapy\arch\windows\__init__.py", line 834, in load_from_powershell
ifaces_ips = get_ips()
File "scapy\arch\windows\__init__.py", line 544, in get_ips
['Description', 'IPAddress']):
File "scapy\arch\windows\__init__.py", line 243, in _exec_query_ps
lines[-1] += sl[0].strip()
IndexError: list index out of range

# Fixed code
def _exec_query_ps(cmd, fields):
    """Execute a PowerShell query, using the cmd command,
    and select and parse the provided fields.
    """
    if not conf.prog.powershell:
        raise OSError("Scapy could not detect powershell !")
    # Build query
    query_cmd = cmd + [
        "|",
        "select %s" % ", ".join(fields),  # select fields
        "|",
        "fl",  # print as a list
        "|",
        "out-string",
        "-Width",
        "4096",
    ]  # do not crop
    lines = []
    # Ask the powershell manager to process the query
    stdout = POWERSHELL_PROCESS.query(query_cmd)
    # Process stdout
    for line in stdout:
        if not line.strip():  # skip empty lines
            continue
        sl = line.split(":", 1)
        if sl[0].strip() not in fields:
            # The previous line was cropped. Let's add the missing part
            lines[-1] += line.strip()
            continue
        else:
            # We put it here to ensure we never return too early,
            # missing some cropped lines
            if len(lines) == len(fields):
                yield lines
                lines = []
            lines.append(sl[1].strip())
    yield lines  # Last buffer won't be returned in the if
# Buggy code
def get_ips(v6=False):
    """Returns all available IPs matching to interfaces, using the windows system.
    Should only be used as a WinPcapy fallback."""
    res = {}
    for descr, ipaddr in exec_query(
        ["Get-WmiObject", "Win32_NetworkAdapterConfiguration"],
        ["Description", "IPAddress"],
    ):
        if ipaddr.strip():
            res[descr] = ipaddr.split(",", 1)[v6].strip("{}").strip()
    return res


# Traceback (IndexError)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "scapy\all.py", line 18, in <module>
from scapy.arch import *
File "scapy\arch\__init__.py", line 73, in <module>
from scapy.arch.windows import *  # noqa F403
File "scapy\arch\windows\__init__.py", line 946, in <module>
IFACES.load_from_powershell()
File "scapy\arch\windows\__init__.py", line 834, in load_from_powershell
ifaces_ips = get_ips()
File "scapy\arch\windows\__init__.py", line 544, in get_ips
['Description', 'IPAddress']):
File "scapy\arch\windows\__init__.py", line 243, in _exec_query_ps
lines[-1] += sl[0].strip()
IndexError: list index out of range

# Fixed code
def get_ips(v6=False):
    """Returns all available IPs matching to interfaces, using the windows system.
    Should only be used as a WinPcapy fallback."""
    res = {}
    for descr, ipaddr in exec_query(
        ["Get-WmiObject", "Win32_NetworkAdapterConfiguration"],
        ["Description", "IPAddress"],
    ):
        if ipaddr.strip():
            # This requires lots of stripping
            ip_string = ipaddr.split(",", 1)[v6].strip("{}").strip()
            res[descr] = [ip.strip() for ip in ip_string.split(",")]
    return res
# Buggy code
def get_ip_from_name(ifname, v6=False):
    """Backward compatibility: indirectly calls get_ips
    Deprecated."""
    return get_ips(v6=v6).get(ifname, "")


# Traceback (IndexError)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "scapy\all.py", line 18, in <module>
from scapy.arch import *
File "scapy\arch\__init__.py", line 73, in <module>
from scapy.arch.windows import *  # noqa F403
File "scapy\arch\windows\__init__.py", line 946, in <module>
IFACES.load_from_powershell()
File "scapy\arch\windows\__init__.py", line 834, in load_from_powershell
ifaces_ips = get_ips()
File "scapy\arch\windows\__init__.py", line 544, in get_ips
['Description', 'IPAddress']):
File "scapy\arch\windows\__init__.py", line 243, in _exec_query_ps
lines[-1] += sl[0].strip()
IndexError: list index out of range

# Fixed code
def get_ip_from_name(ifname, v6=False):
    """Backward compatibility: indirectly calls get_ips
    Deprecated."""
    return get_ips(v6=v6).get(ifname, "")[0]
# Buggy code
def i2h(self, pkt, x):
    return self._fixup_val(super(FlagsField, self).i2h(pkt, x))


# Traceback (ValueError)
ubuntu:/$ scapy
... (welcome info omitted)
p = IP()/TCP()
p = fuzz(p)
p["IP"].show()
###[ IP ]###
version= <RandNum>
ihl= None
tos= 98
len= None
id= <RandShort>
flags= DF+evil
frag= 0
ttl= <RandByte>
proto= tcp
chksum= None
src= 127.0.0.1
dst= 127.0.0.1
\options\
###[ TCP ]###
sport= <RandShort>
dport= <RandShort>
seq= <RandInt>
ack= <RandInt>
dataofs= None
reserved= <RandNum>
flags= SAUC
window= <RandShort>
chksum= None
urgptr= <RandShort>
options= []
# You can query flags repeatedly to see that it's indeed a random value
p["TCP"].flags
<Flag 163 (FSUC)>
p["TCP"].flags
<Flag 414 (SRPACN)>
# But if you try to _fix() it, like you can with other parts of the packet:
p["TCP"].flags._fix()
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 1497, in __getattr__
for flag in attr)
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 1497, in <genexpr>
for flag in attr)
ValueError: substring not found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/scapy/fields.py", line 1499, in __getattr__
return super(FlagValue, self).__getattr__(attr)
AttributeError: 'super' object has no attribute '__getattr__'

# Fixed code
def i2h(self, pkt, x):
    if isinstance(x, VolatileValue):
        return super(FlagsField, self).i2h(pkt, x)
    return self._fixup_val(super(FlagsField, self).i2h(pkt, x))
# Buggy code
def cpu_freq():
    """Alternate implementation using /proc/cpuinfo.
    min and max frequencies are not available and are set to None.
    """
    ret = []
    with open_binary("%s/cpuinfo" % get_procfs_path()) as f:
        for line in f:
            if line.lower().startswith(b"cpu mhz"):
                key, value = line.split(b"\t:", 1)
                ret.append(_common.scpufreq(float(value), None, None))
    return ret


# Traceback (TypeError)
$ s-tui
Traceback (most recent call last):
File "/home/user/venv/bin/s-tui", line 11, in <module>
sys.exit(main())
File "/home/user/venv/lib/python3.6/site-packages/s_tui/s_tui.py", line 927, in main
graph_controller = GraphController(args)
File "/home/user/venv/lib/python3.6/site-packages/s_tui/s_tui.py", line 728, in __init__
self.view = GraphView(self)
File "/home/user/venv/lib/python3.6/site-packages/s_tui/s_tui.py", line 233, in __init__
urwid.WidgetPlaceholder.__init__(self, self.main_window())
File "/home/user/venv/lib/python3.6/site-packages/s_tui/s_tui.py", line 531, in main_window
freq_source = FreqSource(is_admin)
File "/home/user/venv/lib/python3.6/site-packages/s_tui/Sources/FreqSource.py", line 118, in __init__
if self.last_freq >= 0 and self.top_freq <= 0:
TypeError: '<=' not supported between instances of 'NoneType' and 'int'

# Fixed code
def cpu_freq():
    """Alternate implementation using /proc/cpuinfo.
    min and max frequencies are not available and are set to None.
    """
    ret = []
    with open_binary("%s/cpuinfo" % get_procfs_path()) as f:
        for line in f:
            if line.lower().startswith(b"cpu mhz"):
                key, value = line.split(b"\t:", 1)
                ret.append(_common.scpufreq(float(value), 0.0, 0.0))
    return ret
# Buggy code
def _proc_cred(self):
    @wrap_exceptions
    def proc_cred(self):
        return cext.proc_cred(self.pid, self._procfs_path)

    return proc_cred(self)


# Traceback (FileNotFoundError)
Traceback (most recent call last):
File "/data/jon/h2oai/h2oaicore/systemutils.py", line 3100, in find_procs_by_name
for p in psutil.process_iter(attrs=['name']):
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/__init__.py", line 1440, in process_iter
if proc.is_running():
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/__init__.py", line 569, in is_running
return self == Process(self.pid)
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/__init__.py", line 340, in __init__
self._init(pid)
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/__init__.py", line 367, in _init
self.create_time()
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/__init__.py", line 698, in create_time
self._create_time = self._proc.create_time()
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/_pslinux.py", line 1402, in wrapper
return fun(self, *args, **kwargs)
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/_pslinux.py", line 1584, in create_time
values = self._parse_stat_file()
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/_common.py", line 337, in wrapper
return fun(self)
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/_pslinux.py", line 1441, in _parse_stat_file
with open_binary("%s/%s/stat" % (self._procfs_path, self.pid)) as f:
File "/home/jon/.pyenv/versions/3.6.4/lib/python3.6/site-packages/psutil/_pslinux.py", line 187, in open_binary
return open(fname, "rb", **kwargs)
FileNotFoundError: [Errno 2] No such file or directory: '/proc/12825/stat'

# Fixed code
def _proc_cred(self):
    return cext.proc_cred(self.pid, self._procfs_path)
# Buggy code
def wrapper(self, *args, **kwargs):
    try:
        return fun(self, *args, **kwargs)
    except OSError as err:
        raise convert_oserror(err, pid=self.pid, name=self._name)


# Traceback (WindowsError)
======================================================================
ERROR: test_proc_environ (test_process.TestNonUnicode)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\projects\psutil\psutil\tests\test_process.py", line 2054, in test_proc_environ
encode_path(p.environ()['FUNNY_ARG']), funny_path)
File "c:\projects\psutil\psutil\__init__.py", line 772, in environ
return self._proc.environ()
File "c:\projects\psutil\psutil\_pswindows.py", line 536, in wrapper
return fun(self, *args, **kwargs)
File "c:\projects\psutil\psutil\_pswindows.py", line 597, in environ
return parse_environ_block(cext.proc_environ(self.pid))
WindowsError: [Error 299] Only part of a ReadProcessMemory or WriteProcessMemory request was comp

# Fixed code
def wrapper(self, *args, **kwargs):
    delay = 0.0001
    times = 33
    for x in range(times):  # retries for roughly 1 second
        try:
            return fun(self, *args, **kwargs)
        except WindowsError as _:
            err = _
            if err.winerror == ERROR_PARTIAL_COPY:
                time.sleep(delay)
                delay = min(delay * 2, 0.04)
                continue
            else:
                raise
    else:
        msg = (
            "%s retried %s times, converted to AccessDenied as it's "
            "still returning %r" % (fun, times, err)
        )
        raise AccessDenied(pid=self.pid, name=self._name, msg=msg)
# Buggy code
def wrap_exceptions(fun):
    """Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    """

    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except OSError as err:
            if err.errno == errno.ESRCH:
                raise NoSuchProcess(self.pid, self._name)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise

    return wrapper


# Traceback (OSError)
======================================================================
ERROR: psutil.tests.test_process.TestProcess.test_zombie_process
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/travis/build/giampaolo/psutil/psutil/tests/test_process.py", line 1286, in test_zombie_process
zproc.as_dict()
File "/Users/travis/build/giampaolo/psutil/psutil/__init__.py", line 528, in as_dict
ret = meth()
File "/Users/travis/build/giampaolo/psutil/psutil/__init__.py", line 1113, in memory_maps
it = self._proc.memory_maps()
File "/Users/travis/build/giampaolo/psutil/psutil/_psosx.py", line 330, in wrapper
return fun(self, *args, **kwargs)
File "/Users/travis/build/giampaolo/psutil/psutil/_psosx.py", line 571, in memory_maps
return cext.proc_memory_maps(self.pid)
OSError: [Errno 22] Invalid argument

# Fixed code
def wrap_exceptions(fun):
    """Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    """

    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except OSError as err:
            if err.errno == errno.ESRCH:
                raise NoSuchProcess(self.pid, self._name)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise
        except cext.ZombieProcessError:
            raise ZombieProcess(self.pid, self._name, self._ppid)

    return wrapper
# Buggy code
def wrapper(self, *args, **kwargs):
    try:
        return fun(self, *args, **kwargs)
    except OSError as err:
        if err.errno == errno.ESRCH:
            raise NoSuchProcess(self.pid, self._name)
        if err.errno in (errno.EPERM, errno.EACCES):
            raise AccessDenied(self.pid, self._name)
        raise


# Traceback (OSError)
======================================================================
ERROR: psutil.tests.test_process.TestProcess.test_zombie_process
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/travis/build/giampaolo/psutil/psutil/tests/test_process.py", line 1286, in test_zombie_process
zproc.as_dict()
File "/Users/travis/build/giampaolo/psutil/psutil/__init__.py", line 528, in as_dict
ret = meth()
File "/Users/travis/build/giampaolo/psutil/psutil/__init__.py", line 1113, in memory_maps
it = self._proc.memory_maps()
File "/Users/travis/build/giampaolo/psutil/psutil/_psosx.py", line 330, in wrapper
return fun(self, *args, **kwargs)
File "/Users/travis/build/giampaolo/psutil/psutil/_psosx.py", line 571, in memory_maps
return cext.proc_memory_maps(self.pid)
OSError: [Errno 22] Invalid argument

# Fixed code
def wrapper(self, *args, **kwargs):
    try:
        return fun(self, *args, **kwargs)
    except OSError as err:
        if err.errno == errno.ESRCH:
            raise NoSuchProcess(self.pid, self._name)
        if err.errno in (errno.EPERM, errno.EACCES):
            raise AccessDenied(self.pid, self._name)
        raise
    except cext.ZombieProcessError:
        raise ZombieProcess(self.pid, self._name, self._ppid)
# Buggy code
def threads(self):
    with catch_zombie(self):
        rawlist = cext.proc_threads(self.pid)
    retlist = []
    for thread_id, utime, stime in rawlist:
        ntuple = _common.pthread(thread_id, utime, stime)
        retlist.append(ntuple)
    return retlist


# Traceback (OSError)
======================================================================
ERROR: psutil.tests.test_process.TestProcess.test_zombie_process
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/travis/build/giampaolo/psutil/psutil/tests/test_process.py", line 1286, in test_zombie_process
zproc.as_dict()
File "/Users/travis/build/giampaolo/psutil/psutil/__init__.py", line 528, in as_dict
ret = meth()
File "/Users/travis/build/giampaolo/psutil/psutil/__init__.py", line 1113, in memory_maps
it = self._proc.memory_maps()
File "/Users/travis/build/giampaolo/psutil/psutil/_psosx.py", line 330, in wrapper
return fun(self, *args, **kwargs)
File "/Users/travis/build/giampaolo/psutil/psutil/_psosx.py", line 571, in memory_maps
return cext.proc_memory_maps(self.pid)
OSError: [Errno 22] Invalid argument

# Fixed code
def threads(self):
    rawlist = cext.proc_threads(self.pid)
    retlist = []
    for thread_id, utime, stime in rawlist:
        ntuple = _common.pthread(thread_id, utime, stime)
        retlist.append(ntuple)
    return retlist
# Buggy code
def memory_maps(self):
    with catch_zombie(self):
        return cext.proc_memory_maps(self.pid)


# Traceback (OSError)
======================================================================
ERROR: psutil.tests.test_process.TestProcess.test_zombie_process
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/travis/build/giampaolo/psutil/psutil/tests/test_process.py", line 1286, in test_zombie_process
zproc.as_dict()
File "/Users/travis/build/giampaolo/psutil/psutil/__init__.py", line 528, in as_dict
ret = meth()
File "/Users/travis/build/giampaolo/psutil/psutil/__init__.py", line 1113, in memory_maps
it = self._proc.memory_maps()
File "/Users/travis/build/giampaolo/psutil/psutil/_psosx.py", line 330, in wrapper
return fun(self, *args, **kwargs)
File "/Users/travis/build/giampaolo/psutil/psutil/_psosx.py", line 571, in memory_maps
return cext.proc_memory_maps(self.pid)
OSError: [Errno 22] Invalid argument

# Fixed code
def memory_maps(self):
    return cext.proc_memory_maps(self.pid)
# Buggy code
def exe(self):
    # Note: os.path.exists(path) may return False even if the file
    # is there, see:
    # http://stackoverflow.com/questions/3112546/os-path-exists-lies

    # see https://github.com/giampaolo/psutil/issues/414
    # see https://github.com/giampaolo/psutil/issues/528
    if self.pid in (0, 4):
        raise AccessDenied(self.pid, self._name)
    exe = cext.proc_exe(self.pid)
    exe = convert_dos_path(exe)
    return py2_strencode(exe)


# Traceback (WindowsError)
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
import psutil
[p for p in psutil.process_iter()]
[psutil.Process(pid=0, name='System Idle Process', started='2018-11-06 04:18:12'), psutil.Process(pid=4, name='System', started='2018-11-06 04:18:12'), Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\psutil\__init__.py", line 395, in __str__
info["name"] = self.name()
File "C:\Python27\lib\site-packages\psutil\__init__.py", line 609, in name
name = self._proc.name()
File "C:\Python27\lib\site-packages\psutil\_pswindows.py", line 635, in wrapper
return fun(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\psutil\_pswindows.py", line 687, in name
return py2_strencode(os.path.basename(self.exe()))
File "C:\Python27\lib\site-packages\psutil\_pswindows.py", line 635, in wrapper
return fun(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\psutil\_pswindows.py", line 701, in exe
return py2_strencode(convert_dos_path(cext.proc_exe(self.pid)))
WindowsError: [Error 0] The operation completed successfully

# Fixed code
def exe(self):
    # Dual implementation, see:
    # https://github.com/giampaolo/psutil/pull/1413
    if not IS_WIN_XP:
        exe = cext.proc_exe(self.pid)
    else:
        if self.pid in (0, 4):
            # https://github.com/giampaolo/psutil/issues/414
            # https://github.com/giampaolo/psutil/issues/528
            raise AccessDenied(self.pid, self._name)
        exe = cext.proc_exe(self.pid)
        exe = convert_dos_path(exe)
    return py2_strencode(exe)
# Buggy code
def exe(self):
    # Note: os.path.exists(path) may return False even if the file
    # is there, see:
    # http://stackoverflow.com/questions/3112546/os-path-exists-lies

    # see https://github.com/giampaolo/psutil/issues/414
    # see https://github.com/giampaolo/psutil/issues/528
    if self.pid in (0, 4):
        raise AccessDenied(self.pid, self._name)
    return py2_strencode(convert_dos_path(cext.proc_exe(self.pid)))


# Traceback (WindowsError)
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
import psutil
[p for p in psutil.process_iter()]
[psutil.Process(pid=0, name='System Idle Process', started='2018-11-06 04:18:12'), psutil.Process(pid=4, name='System', started='2018-11-06 04:18:12'), Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\psutil\__init__.py", line 395, in __str__
info["name"] = self.name()
File "C:\Python27\lib\site-packages\psutil\__init__.py", line 609, in name
name = self._proc.name()
File "C:\Python27\lib\site-packages\psutil\_pswindows.py", line 635, in wrapper
return fun(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\psutil\_pswindows.py", line 687, in name
return py2_strencode(os.path.basename(self.exe()))
File "C:\Python27\lib\site-packages\psutil\_pswindows.py", line 635, in wrapper
return fun(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\psutil\_pswindows.py", line 701, in exe
return py2_strencode(convert_dos_path(cext.proc_exe(self.pid)))
WindowsError: [Error 0] The operation completed successfully

# Fixed code
def exe(self):
    # Note: os.path.exists(path) may return False even if the file
    # is there, see:
    # http://stackoverflow.com/questions/3112546/os-path-exists-lies

    # see https://github.com/giampaolo/psutil/issues/414
    # see https://github.com/giampaolo/psutil/issues/528
    if self.pid in (0, 4):
        raise AccessDenied(self.pid, self._name)
    exe = cext.proc_exe(self.pid)
    exe = convert_dos_path(exe)
    return py2_strencode(exe)
# Buggy code
def cat(fname, fallback=_DEFAULT, binary=True):
    """Return file content.
    fallback: the value returned in case the file does not exist or
              cannot be read
    binary: whether to open the file in binary or text mode.
    """
    try:
        with open_binary(fname) if binary else open_text(fname) as f:
            return f.read().strip()
    except IOError:
        if fallback is not _DEFAULT:
            return fallback
        else:
            raise


# Traceback (ValueError)
Traceback (most recent call last):
File "/usr/lib/python-exec/python2.7/s-tui", line 11, in <module>
load_entry_point('s-tui==0.7.5', 'console_scripts', 's-tui')()
File "/usr/lib64/python2.7/site-packages/s_tui/s_tui.py", line 854, in main
graph_controller = GraphController(args)
File "/usr/lib64/python2.7/site-packages/s_tui/s_tui.py", line 680, in __init__
self.view = GraphView(self)
File "/usr/lib64/python2.7/site-packages/s_tui/s_tui.py", line 210, in __init__
self.temp_sensors_menu = TempSensorsMenu(self.on_sensors_menu_close)
File "/usr/lib64/python2.7/site-packages/s_tui/TempSensorsMenu.py", line 70, in __init__
sensors_dict = psutil.sensors_temperatures()
File "/usr/lib64/python2.7/site-packages/psutil/__init__.py", line 2194, in sensors_temperatures
rawdict = _psplatform.sensors_temperatures()
File "/usr/lib64/python2.7/site-packages/psutil/_pslinux.py", line 1150, in sensors_temperatures
current = float(cat(path)) / 1000.0
ValueError: could not convert string to float:

# Fixed code
def cat(fname, fallback=_DEFAULT, binary=True):
    """Return file content.
    fallback: the value returned in case the file does not exist or
              cannot be read
    binary: whether to open the file in binary or text mode.
    """
    try:
        with open_binary(fname) if binary else open_text(fname) as f:
            return f.read().strip()
    except (IOError, OSError):
        if fallback is not _DEFAULT:
            return fallback
        else:
            raise
# Buggy code
def _proc_cred(self):
    return cext.proc_cred(self.pid, self._procfs_path)


# Traceback (OSError)
p = psutil.Process(960)
p.name()
'xntpd'
p.nice()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/venv/lib/python3.5/site-packages/psutil/__init__.py", line 755, in nice
return self._proc.nice_get()
File "/path/to/venv/lib/python3.5/site-packages/psutil/_pssunos.py", line 346, in wrapper
return fun(self, *args, **kwargs)
File "/path/to/venv/lib/python3.5/site-packages/psutil/_pssunos.py", line 451, in nice_get
return cext_posix.getpriority(self.pid)
OSError: [Errno 22] Invalid argument

# Fixed code
def _proc_cred(self):
    @wrap_exceptions
    def proc_cred(self):
        return cext.proc_cred(self.pid, self._procfs_path)

    return proc_cred(self)
# Buggy code
def nice_get(self):
    # Note #1: for some reason getpriority(3) return ESRCH (no such
    # process) for certain low-pid processes, no matter what (even
    # as root).
    # The process actually exists though, as it has a name,
    # creation time, etc.
    # The best thing we can do here appears to be raising AD.
    # Note: tested on Solaris 11; on Open Solaris 5 everything is
    # fine.
    #
    # Note #2: we also can get niceness from /proc/pid/psinfo
    # but it's wrong, see:
    # https://github.com/giampaolo/psutil/issues/1082
    try:
        return cext_posix.getpriority(self.pid)
    except EnvironmentError as err:
        # 48 is 'operation not supported' but errno does not expose
        # it. It occurs for low system pids.
        if err.errno in (errno.ENOENT, errno.ESRCH, 48):
            if pid_exists(self.pid):
                raise AccessDenied(self.pid, self._name)
        raise


# Traceback (OSError)
p = psutil.Process(960)
p.name()
'xntpd'
p.nice()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/venv/lib/python3.5/site-packages/psutil/__init__.py", line 755, in nice
return self._proc.nice_get()
File "/path/to/venv/lib/python3.5/site-packages/psutil/_pssunos.py", line 346, in wrapper
return fun(self, *args, **kwargs)
File "/path/to/venv/lib/python3.5/site-packages/psutil/_pssunos.py", line 451, in nice_get
return cext_posix.getpriority(self.pid)
OSError: [Errno 22] Invalid argument

# Fixed code
def nice_get(self):
    # Note #1: getpriority(3) doesn't work for realtime processes.
    # Psinfo is what ps uses, see:
    # https://github.com/giampaolo/psutil/issues/1194
    return self._proc_basic_info()[proc_info_map["nice"]]
# Buggy code
def uids(self):
    real, effective, saved, _, _, _ = self._proc_cred()
    return _common.puids(real, effective, saved)


# Traceback (OSError)
p = psutil.Process(960)
p.name()
'xntpd'
p.nice()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/venv/lib/python3.5/site-packages/psutil/__init__.py", line 755, in nice
return self._proc.nice_get()
File "/path/to/venv/lib/python3.5/site-packages/psutil/_pssunos.py", line 346, in wrapper
return fun(self, *args, **kwargs)
File "/path/to/venv/lib/python3.5/site-packages/psutil/_pssunos.py", line 451, in nice_get
return cext_posix.getpriority(self.pid)
OSError: [Errno 22] Invalid argument

# Fixed code
def uids(self):
    try:
        real, effective, saved, _, _, _ = self._proc_cred()
    except AccessDenied:
        real = self._proc_basic_info()[proc_info_map["uid"]]
        effective = self._proc_basic_info()[proc_info_map["euid"]]
        saved = None
    return _common.puids(real, effective, saved)
# Buggy code
def gids(self):
    _, _, _, real, effective, saved = self._proc_cred()
    return _common.puids(real, effective, saved)


# Traceback (OSError)
p = psutil.Process(960)
p.name()
'xntpd'
p.nice()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/venv/lib/python3.5/site-packages/psutil/__init__.py", line 755, in nice
return self._proc.nice_get()
File "/path/to/venv/lib/python3.5/site-packages/psutil/_pssunos.py", line 346, in wrapper
return fun(self, *args, **kwargs)
File "/path/to/venv/lib/python3.5/site-packages/psutil/_pssunos.py", line 451, in nice_get
return cext_posix.getpriority(self.pid)
OSError: [Errno 22] Invalid argument

# Fixed code
def gids(self):
    try:
        _, _, _, real, effective, saved = self._proc_cred()
    except AccessDenied:
        real = self._proc_basic_info()[proc_info_map["gid"]]
        effective = self._proc_basic_info()[proc_info_map["egid"]]
        saved = None
    return _common.puids(real, effective, saved)
# Buggy code
def wait(self, timeout=None):
    if timeout is None:
        cext_timeout = cext.INFINITE
    else:
        # WaitForSingleObject() expects time in milliseconds
        cext_timeout = int(timeout * 1000)
    ret = cext.proc_wait(self.pid, cext_timeout)
    if ret == WAIT_TIMEOUT:
        raise TimeoutExpired(timeout, self.pid, self._name)
    return ret


# Traceback (AssertionError)
Traceback (most recent call last):
File "c:\projects\psutil\psutil\tests\test_misc.py", line 923, in test_reap_children
reap_children()
File "c:\projects\psutil\psutil\tests\__init__.py", line 438, in reap_children
assert_gone(pid)
File "c:\projects\psutil\psutil\tests\__init__.py", line 388, in assert_gone
assert not psutil.pid_exists(pid), pid
AssertionError: 3028
======================================================================

# Fixed code
def wait(self, timeout=None):
    if timeout is None:
        cext_timeout = cext.INFINITE
    else:
        # WaitForSingleObject() expects time in milliseconds
        cext_timeout = int(timeout * 1000)
    while True:
        ret = cext.proc_wait(self.pid, cext_timeout)
        if ret == WAIT_TIMEOUT:
            raise TimeoutExpired(timeout, self.pid, self._name)
        if timeout is None and pid_exists(self.pid):
            continue
        return ret
# Buggy code
def wait(self, timeout=None):
    if timeout is None:
        cext_timeout = cext.INFINITE
    else:
        # WaitForSingleObject() expects time in milliseconds
        cext_timeout = int(timeout * 1000)
    while True:
        ret = cext.proc_wait(self.pid, cext_timeout)
        if ret == WAIT_TIMEOUT:
            raise TimeoutExpired(timeout, self.pid, self._name)
        if timeout is None and pid_exists(self.pid):
            continue
        return ret


# Traceback (AssertionError)
Traceback (most recent call last):
File "c:\projects\psutil\psutil\tests\test_misc.py", line 923, in test_reap_children
reap_children()
File "c:\projects\psutil\psutil\tests\__init__.py", line 438, in reap_children
assert_gone(pid)
File "c:\projects\psutil\psutil\tests\__init__.py", line 388, in assert_gone
assert not psutil.pid_exists(pid), pid
AssertionError: 3028
======================================================================

# Fixed code
def wait(self, timeout=None):
    if timeout is None:
        cext_timeout = cext.INFINITE
    else:
        # WaitForSingleObject() expects time in milliseconds
        cext_timeout = int(timeout * 1000)
    while True:
        ret = cext.proc_wait(self.pid, cext_timeout)
        if ret == WAIT_TIMEOUT:
            raise TimeoutExpired(timeout, self.pid, self._name)
        if pid_exists(self.pid):
            if timeout is None:
                continue
            else:
                raise TimeoutExpired(timeout, self.pid, self._name)
        return ret
# Buggy code
def nice_get(self):
    # For some reason getpriority(3) return ESRCH (no such process)
    # for certain low-pid processes, no matter what (even as root).
    # The process actually exists though, as it has a name,
    # creation time, etc.
    # The best thing we can do here appears to be raising AD.
    # Note: tested on Solaris 11; on Open Solaris 5 everything is
    # fine.
    try:
        return cext_posix.getpriority(self.pid)
    except EnvironmentError as err:
        # 48 is 'operation not supported' but errno does not expose
        # it. It occurs for low system pids.
        if err.errno in (errno.ENOENT, errno.ESRCH, 48):
            if pid_exists(self.pid):
                raise AccessDenied(self.pid, self._name)
        raise


# Traceback (AssertionError)
======================================================================
FAIL: psutil.tests.test_posix.TestProcess.test_nice
----------------------------------------------------------------------
Traceback (most recent call last):
File "psutil/tests/test_posix.py", line 208, in test_nice
self.assertEqual(ps_nice, psutil_nice)
AssertionError: 20 != 0

# Fixed code
def nice_get(self):
    # Note #1: for some reason getpriority(3) return ESRCH (no such
    # process) for certain low-pid processes, no matter what (even
    # as root).
    # The process actually exists though, as it has a name,
    # creation time, etc.
    # The best thing we can do here appears to be raising AD.
    # Note: tested on Solaris 11; on Open Solaris 5 everything is
    # fine.
    #
    # Note #2: we also can get niceness from /proc/pid/psinfo
    # but it's wrong, see:
    # https://github.com/giampaolo/psutil/issues/1082
    try:
        return cext_posix.getpriority(self.pid)
    except EnvironmentError as err:
        # 48 is 'operation not supported' but errno does not expose
        # it. It occurs for low system pids.
        if err.errno in (errno.ENOENT, errno.ESRCH, 48):
            if pid_exists(self.pid):
                raise AccessDenied(self.pid, self._name)
        raise