def virtual_memory(): total, free, buffers, shared, _, _ = cext.linux_sysinfo() cached = active = inactive = None f = open('/proc/meminfo', 'rb') CACHED, ACTIVE, INACTIVE = b("Cached:"), b("Active:"), b("Inactive:") try: for line in f: if line.startswith(CACHED): cached = int(line.split()[1]) * 1024 elif line.startswith(ACTIVE): active = int(line.split()[1]) * 1024 elif line.startswith(INACTIVE): inactive = int(line.split()[1]) * 1024 if (cached is not None and active is not None and inactive is not None): break else: # we might get here when dealing with exotic Linux flavors, see: # http://code.google.com/p/psutil/issues/detail?id=313 msg = "'cached', 'active' and 'inactive' memory stats couldn't " \ "be determined and were set to 0" warnings.warn(msg, RuntimeWarning) cached = active = inactive = 0 finally: f.close() avail = free + buffers + cached used = total - free percent = usage_percent((total - avail), total, _round=1) return svmem(total, avail, percent, used, free, active, inactive, buffers, cached)
def threads(self): thread_ids = os.listdir("/proc/%s/task" % self.pid) thread_ids.sort() retlist = [] hit_enoent = False for thread_id in thread_ids: try: f = open("/proc/%s/task/%s/stat" % (self.pid, thread_id), 'rb') except EnvironmentError: err = sys.exc_info()[1] if err.errno == errno.ENOENT: # no such file or directory; it means thread # disappeared on us hit_enoent = True continue raise try: st = f.read().strip() finally: f.close() # ignore the first two values ("pid (exe)") st = st[st.find(b(')')) + 2:] values = st.split(b(' ')) utime = float(values[11]) / CLOCK_TICKS stime = float(values[12]) / CLOCK_TICKS ntuple = _common.pthread(int(thread_id), utime, stime) retlist.append(ntuple) if hit_enoent: # raise NSP if the process disappeared on us os.stat('/proc/%s' % self.pid) return retlist
def virtual_memory(): total, free, buffers, shared, _, _ = cext.linux_sysinfo() cached = active = inactive = None f = open('/proc/meminfo', 'rb') CACHED, ACTIVE, INACTIVE = b("Cached:"), b("Active:"), b("Inactive:") try: for line in f: if line.startswith(CACHED): cached = int(line.split()[1]) * 1024 elif line.startswith(ACTIVE): active = int(line.split()[1]) * 1024 elif line.startswith(INACTIVE): inactive = int(line.split()[1]) * 1024 if (cached is not None and active is not None and inactive is not None): break else: # we might get here when dealing with exotic Linux flavors, see: # https://github.com/giampaolo/psutil/issues/313 msg = "'cached', 'active' and 'inactive' memory stats couldn't " \ "be determined and were set to 0" warnings.warn(msg, RuntimeWarning) cached = active = inactive = 0 finally: f.close() avail = free + buffers + cached used = total - free percent = usage_percent((total - avail), total, _round=1) return svmem(total, avail, percent, used, free, active, inactive, buffers, cached)
def swap_memory(): _, _, _, _, total, free = cext.linux_sysinfo() used = total - free percent = usage_percent(used, total, _round=1) # get pgin/pgouts f = open("/proc/vmstat", "rb") SIN, SOUT = b('pswpin'), b('pswpout') sin = sout = None try: for line in f: # values are expressed in 4 kilo bytes, we want bytes instead if line.startswith(SIN): sin = int(line.split(b(' '))[1]) * 4 * 1024 elif line.startswith(SOUT): sout = int(line.split(b(' '))[1]) * 4 * 1024 if sin is not None and sout is not None: break else: # we might get here when dealing with exotic Linux flavors, see: # https://github.com/giampaolo/psutil/issues/313 msg = "'sin' and 'sout' swap memory stats couldn't " \ "be determined and were set to 0" warnings.warn(msg, RuntimeWarning) sin = sout = 0 finally: f.close() return _common.sswap(total, used, free, percent, sin, sout)
def swap_memory(): _, _, _, _, total, free = cext.linux_sysinfo() used = total - free percent = usage_percent(used, total, _round=1) # get pgin/pgouts f = open("/proc/vmstat", "rb") SIN, SOUT = b('pswpin'), b('pswpout') sin = sout = None try: for line in f: # values are expressed in 4 kilo bytes, we want bytes instead if line.startswith(SIN): sin = int(line.split(b(' '))[1]) * 4 * 1024 elif line.startswith(SOUT): sout = int(line.split(b(' '))[1]) * 4 * 1024 if sin is not None and sout is not None: break else: # we might get here when dealing with exotic Linux flavors, see: # http://code.google.com/p/psutil/issues/detail?id=313 msg = "'sin' and 'sout' swap memory stats couldn't " \ "be determined and were set to 0" warnings.warn(msg, RuntimeWarning) sin = sout = 0 finally: f.close() return _common.sswap(total, used, free, percent, sin, sout)
def cpu_times(self): f = open("/proc/%s/stat" % self.pid, 'rb') try: st = f.read().strip() finally: f.close() # ignore the first two values ("pid (exe)") st = st[st.find(b(')')) + 2:] values = st.split(b(' ')) utime = float(values[11]) / CLOCK_TICKS stime = float(values[12]) / CLOCK_TICKS return _common.pcputimes(utime, stime)
def create_time(self): f = open("/proc/%s/stat" % self.pid, 'rb') try: st = f.read().strip() finally: f.close() # ignore the first two values ("pid (exe)") st = st[st.rfind(b(')')) + 2:] values = st.split(b(' ')) # According to documentation, starttime is in field 21 and the # unit is jiffies (clock ticks). # We first divide it for clock ticks and then add uptime returning # seconds since the epoch, in UTC. # Also use cached value if available. bt = BOOT_TIME or boot_time() return (float(values[19]) / CLOCK_TICKS) + bt
def num_threads(self): f = open("/proc/%s/status" % self.pid, "rb") try: THREADS = b("Threads:") for line in f: if line.startswith(THREADS): return int(line.split()[1]) raise NotImplementedError("line not found") finally: f.close()
def num_ctx_switches(self): vol = unvol = None f = open("/proc/%s/status" % self.pid, "rb") VOLUNTARY = b("voluntary_ctxt_switches") NON_VOLUNTARY = b("nonvoluntary_ctxt_switches") try: for line in f: if line.startswith(VOLUNTARY): vol = int(line.split()[1]) elif line.startswith(NON_VOLUNTARY): unvol = int(line.split()[1]) if vol is not None and unvol is not None: return _common.pctxsw(vol, unvol) raise NotImplementedError( "'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'" "fields were not found in /proc/%s/status; the kernel is " "probably older than 2.6.23" % self.pid) finally: f.close()
def ppid(self): f = open("/proc/%s/status" % self.pid, 'rb') try: PPID = b("PPid:") for line in f: if line.startswith(PPID): # PPid: nnnn return int(line.split()[1]) raise NotImplementedError("line not found") finally: f.close()
def gids(self): f = open("/proc/%s/status" % self.pid, 'rb') try: GID = b('Gid:') for line in f: if line.startswith(GID): _, real, effective, saved, fs = line.split() return _common.pgids(int(real), int(effective), int(saved)) raise NotImplementedError("line not found") finally: f.close()
def terminal(self): tmap = _psposix._get_terminal_map() f = open("/proc/%s/stat" % self.pid, 'rb') try: tty_nr = int(f.read().split(b(' '))[6]) finally: f.close() try: return tmap[tty_nr] except KeyError: return None
def status(self): f = open("/proc/%s/status" % self.pid, 'rb') try: STATE = b("State:") for line in f: if line.startswith(STATE): letter = line.split()[1] if PY3: letter = letter.decode() # XXX is '?' legit? (we're not supposed to return # it anyway) return PROC_STATUSES.get(letter, '?') finally: f.close()
def boot_time(): """Return the system boot time expressed in seconds since the epoch.""" global BOOT_TIME f = open('/proc/stat', 'rb') try: BTIME = b('btime') for line in f: if line.startswith(BTIME): ret = float(line.strip().split()[1]) BOOT_TIME = ret return ret raise RuntimeError("line 'btime' not found") finally: f.close()
def io_counters(self): fname = "/proc/%s/io" % self.pid f = open(fname, 'rb') SYSCR, SYSCW = b("syscr"), b("syscw") READ_BYTES, WRITE_BYTES = b("read_bytes"), b("write_bytes") try: rcount = wcount = rbytes = wbytes = None for line in f: if rcount is None and line.startswith(SYSCR): rcount = int(line.split()[1]) elif wcount is None and line.startswith(SYSCW): wcount = int(line.split()[1]) elif rbytes is None and line.startswith(READ_BYTES): rbytes = int(line.split()[1]) elif wbytes is None and line.startswith(WRITE_BYTES): wbytes = int(line.split()[1]) for x in (rcount, wcount, rbytes, wbytes): if x is None: raise NotImplementedError( "couldn't read all necessary info from %r" % fname) return _common.pio(rcount, wcount, rbytes, wbytes) finally: f.close()
def cpu_count_physical(): """Return the number of physical CPUs in the system.""" f = open('/proc/cpuinfo', 'rb') try: lines = f.readlines() finally: f.close() found = set() PHYSICAL_ID = b('physical id') for line in lines: if line.lower().startswith(PHYSICAL_ID): found.add(line.strip()) if found: return len(found) else: return None # mimic os.cpu_count()
def per_cpu_times(): """Return a list of namedtuple representing the CPU times for every CPU available on the system. """ cpus = [] f = open('/proc/stat', 'rb') try: # get rid of the first line which refers to system wide CPU stats f.readline() CPU = b('cpu') for line in f: if line.startswith(CPU): values = line.split() fields = values[1:len(scputimes._fields) + 1] fields = [float(x) / CLOCK_TICKS for x in fields] entry = scputimes(*fields) cpus.append(entry) return cpus finally: f.close()
def disk_partitions(all=False): """Return mounted disk partitions as a list of nameduples""" phydevs = [] f = open("/proc/filesystems", "rb") try: NODEV = b("nodev") for line in f: if not line.startswith(NODEV): phydevs.append(line.strip()) finally: f.close() retlist = [] partitions = cext.disk_partitions() for partition in partitions: device, mountpoint, fstype, opts = partition if device == 'none': device = '' if not all: if device == '' or fstype not in phydevs: continue ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) retlist.append(ntuple) return retlist
def cpu_count_logical(): """Return the number of logical CPUs in the system.""" try: return os.sysconf("SC_NPROCESSORS_ONLN") except ValueError: # as a second fallback we try to parse /proc/cpuinfo num = 0 f = open('/proc/cpuinfo', 'rb') try: lines = f.readlines() finally: f.close() PROCESSOR = b('processor') for line in lines: if line.lower().startswith(PROCESSOR): num += 1 # unknown format (e.g. amrel/sparc architectures), see: # http://code.google.com/p/psutil/issues/detail?id=200 # try to parse /proc/stat as a last resort if num == 0: f = open('/proc/stat', 'rt') try: lines = f.readlines() finally: f.close() search = re.compile('cpu\d') for line in lines: line = line.split(' ')[0] if search.match(line): num += 1 if num == 0: # mimic os.cpu_count() return None return num
def cpu_count_logical(): """Return the number of logical CPUs in the system.""" try: return os.sysconf("SC_NPROCESSORS_ONLN") except ValueError: # as a second fallback we try to parse /proc/cpuinfo num = 0 f = open('/proc/cpuinfo', 'rb') try: lines = f.readlines() finally: f.close() PROCESSOR = b('processor') for line in lines: if line.lower().startswith(PROCESSOR): num += 1 # unknown format (e.g. amrel/sparc architectures), see: # https://github.com/giampaolo/psutil/issues/200 # try to parse /proc/stat as a last resort if num == 0: f = open('/proc/stat', 'rt') try: lines = f.readlines() finally: f.close() search = re.compile('cpu\d') for line in lines: line = line.split(' ')[0] if search.match(line): num += 1 if num == 0: # mimic os.cpu_count() return None return num
def pids(): """Returns a list of PIDs currently running on the system.""" return [int(x) for x in os.listdir(b('/proc')) if x.isdigit()]