Best Python code snippet using autotest_python
mem
Source:mem
...157 if len(line) > 2 and line[2] == 'kB':158 value *= 1024159 meminfo[line[0][:-1]] = value160 return meminfo161def is_linux_meminfo(meminfo):162 return "PageTables" in meminfo and "Writeback" in meminfo and "Committed_AS" in meminfo163def inventory_mem_linux(info):164 meminfo = parse_proc_meminfo_bytes(info)165 if is_linux_meminfo(meminfo):166 return [ (None, {}) ]167def check_mem_levels(title, used, total, levels, of_what=None, of_value=None, show_percentage=False, show_free=False):168 if of_value == None:169 of_value = total # Reference for percentage levels170 state = 0171 if of_what:172 if show_free:173 value = total - used174 else:175 value = used176 infotext = "%s: %s" % (title, get_bytes_human_readable(value))177 else:178 infotext = "%s used: %s of %s" % (179 title, get_bytes_human_readable(used), get_bytes_human_readable(total))180 perc_shown = False181 if levels and levels != "ignore":182 how = levels[0]183 if how == "predictive":184 return 3, "Predictive levels for memory check not yet implemented"185 # TODO: Hier brauchen wir den Namen der RRD-variable! Das klappt aber186 # nicht, wenn hier Werte zusammengerechnet wurden. Wir sollten die187 # Predictive Levels nur für ausgewählte Werte zulassen.188 # return check_levels(used, levels[1], unit = "GB")189 warn, crit = levels[1]190 if how.startswith("perc_"):191 perc_used = 100.0 * float(used) / of_value192 perc_free = 100 - perc_used193 if how == "perc_used":194 if of_what:195 t = " of " + of_what196 else:197 t = ""198 levels_text = " (%.1f%%%s, " % (perc_used, t)199 if perc_used >= crit:200 state = 2201 elif perc_used >= warn:202 state = 1203 elif how == "perc_free":204 if of_what:205 t = "of " + of_what206 else:207 t = "free"208 levels_text = " (%.1f%% %s, " % (perc_free, t)209 if perc_free < crit:210 state = 2211 elif perc_free < warn:212 state = 1213 if state:214 perc_shown = True215 infotext += levels_text + "levels at %.1f%%/%.1f%%)" % (warn, crit)216 else:217 if how == "abs_used":218 if used >= crit:219 state = 2220 elif used >= warn:221 state = 1222 else:223 free = total - used224 if free < crit:225 state = 2226 elif free < warn:227 state = 1228 if state:229 infotext += " (levels at %s/%s)" % (get_bytes_human_readable(warn), get_bytes_human_readable(crit))230 if not perc_shown and show_percentage:231 infotext += " (%.1f%%)" % (100.0 * float(used) / of_value)232 return state, infotext233def check_mem_linux(_no_item, params, info):234 meminfo = parse_proc_meminfo_bytes(info)235 # SReclaimable is not available for older kernels236 if "SReclaimable" not in meminfo:237 meminfo["SReclaimable"] = 0238 meminfo["SUnreclaim"] = meminfo["Slab"]239 # Compute memory used by caches, that can be considered "free"240 meminfo["Caches"] = meminfo["Cached"] + meminfo["Buffers"] \241 + meminfo["SwapCached"] + meminfo["SReclaimable"]242 # RAM243 meminfo["MemUsed"] = meminfo["MemTotal"] - meminfo["MemFree"] - meminfo["Caches"]244 yield check_mem_levels("RAM", meminfo["MemUsed"], meminfo["MemTotal"],245 params.get("levels_ram"), show_percentage=not meminfo["SwapTotal"])246 # Swap - but only if available247 meminfo["SwapUsed"] = meminfo["SwapTotal"] - meminfo["SwapFree"]248 if meminfo["SwapTotal"]:249 yield check_mem_levels("Swap", meminfo["SwapUsed"], meminfo["SwapTotal"],250 params.get("levels_swap"))251 # Total virtual memory252 meminfo["TotalTotal"] = meminfo["MemTotal"] + meminfo["SwapTotal"]253 meminfo["TotalUsed"] = meminfo["MemUsed"] + meminfo["SwapUsed"]254 r = check_mem_levels("Total virtual memory", meminfo["TotalUsed"], meminfo["TotalTotal"],255 params.get("levels_virtual"), show_percentage=True)256 if r[0] or meminfo["SwapTotal"]:257 yield r # only display if there is swap or status is non-OK258 # Total memory / in relation to RAM259 r = check_mem_levels("RAM + Swap", meminfo["TotalUsed"], meminfo["TotalTotal"],260 params.get("levels_total"), of_what = "RAM", of_value = meminfo["MemTotal"])261 if r[0]:262 yield r # only display if non-OK263 # Shared memory264 if "Shmem" in meminfo:265 r = check_mem_levels("Shared memory", meminfo["Shmem"], meminfo["MemTotal"],266 params.get("levels_shm"), of_what = "RAM")267 if r[0]:268 yield r # only display if non-OK269 # Page tables270 r = check_mem_levels("Page tables", meminfo["PageTables"], meminfo["MemTotal"],271 params.get("levels_pagetables"), of_what = "RAM")272 if r[0]:273 yield r # only display if non-OK274 # Disk Writeback275 meminfo["Pending"] = \276 meminfo["Dirty"] \277 + meminfo.get("Writeback", 0) \278 + meminfo.get("NFS_Unstable", 0) \279 + meminfo.get("Bounce", 0) \280 + meminfo.get("WritebackTmp", 0)281 r = check_mem_levels("Disk Writeback", meminfo["Pending"], meminfo["MemTotal"],282 params.get("levels_writeback"), of_what = "RAM")283 if r[0]:284 yield r # only display if non-OK285 # Committed memory286 r = check_mem_levels("Committed", meminfo["Committed_AS"], meminfo["TotalTotal"],287 params.get("levels_committed"), of_what = "RAM + Swap")288 if r[0]:289 yield r # only display if non-OK290 # Commit limit291 if "CommitLimit" in meminfo:292 r = check_mem_levels("Commit Limit", meminfo["TotalTotal"] - meminfo["CommitLimit"],293 meminfo["TotalTotal"], params.get("levels_commitlimit"), of_what = "RAM + Swap")294 if r[0]:295 yield r # only display if non-OK296 # VMalloc297 r = check_mem_levels("Largest Free VMalloc Chunk", meminfo["VmallocTotal"] - meminfo["VmallocChunk"],298 meminfo["VmallocTotal"], params.get("levels_vmalloc"), of_what = "VMalloc Area", show_free=True)299 if r[0]:300 yield r # only display if non-OK301 # HardwareCorrupted302 hwc = meminfo.get("HardwareCorrupted")303 if hwc:304 yield 2, "Hardware defect of %s" % get_bytes_human_readable(hwc)305 # Now send performance data. We simply output *all* fields of meminfo306 # except for a few really useless values307 perfdata = []308 items = meminfo.items()309 items.sort()310 for name, value in items:311 if name.startswith("DirectMap"):312 continue313 if name.startswith("Vmalloc") and meminfo["VmallocTotal"] > 2**40: # useless on 64 Bit system314 continue315 if name.startswith("Huge"):316 if meminfo["HugePages_Total"] == 0: # omit useless data317 continue318 if name == "Hugepagesize":319 continue # not needed320 value = value * meminfo["Hugepagesize"] # convert number to actual memory size321 perfdata.append((camelcase_to_underscored(name.replace("(", "_").replace(")","")), value))322 yield 0, "", perfdata323check_info["mem.linux"] = {324 'check_function': check_mem_linux,325 'inventory_function': inventory_mem_linux,326 'service_description': 'Memory',327 'default_levels_variable': 'mem_linux_default_levels',328 'has_perfdata': True,329 'group': 'memory_linux',330}331#.332# .--mem.used------------------------------------------------------------.333# | _ |334# | _ __ ___ ___ _ __ ___ _ _ ___ ___ __| | |335# | | '_ ` _ \ / _ \ '_ ` _ \ | | | / __|/ _ \/ _` | |336# | | | | | | | __/ | | | | || |_| \__ \ __/ (_| | |337# | |_| |_| |_|\___|_| |_| |_(_)__,_|___/\___|\__,_| |338# | |339# +----------------------------------------------------------------------+340# | Memory check that takes into account the swap space. This check is |341# | used for unixoide operating systems. |342# '----------------------------------------------------------------------'343def parse_proc_meminfo(info):344 return dict([ (i[0][:-1], int(i[1])) for i in info ])345# The following variable is obsolete. It is kept here so that Check_MK346# won't fail if it's found in main.mk347mem_extended_perfdata = None348def inventory_mem_used(info):349 meminfo = parse_proc_meminfo(info)350 if "MemTotal" in meminfo \351 and "PageTotal" not in meminfo \352 and not is_linux_meminfo(meminfo): # handled by more modern check353 return [(None, {})]354def check_mem_used(_no_item, params, info):355 meminfo = parse_proc_meminfo(info)356 return check_memory(params, meminfo)357check_info['mem.used'] = {358 "check_function" : check_mem_used,359 "inventory_function" : inventory_mem_used,360 "service_description" : "Memory used",361 "has_perfdata" : True,362 "group" : "memory",363 "default_levels_variable" : "memory_default_levels",364 "includes" : [ "mem.include" ],365}366#.367# .--mem.win-------------------------------------------------------------.368# | _ |369# | _ __ ___ ___ _ __ ___ __ _(_)_ __ |370# | | '_ ` _ \ / _ \ '_ ` _ \\ \ /\ / / | '_ \ |371# | | | | | | | __/ | | | | |\ V V /| | | | | |372# | |_| |_| |_|\___|_| |_| |_(_)_/\_/ |_|_| |_| |373# | |374# +----------------------------------------------------------------------+375# | Windows now has a dedicated memory check that reflect the special |376# | nature of the page file. |377# '----------------------------------------------------------------------'378# Special memory and page file check for Windows379factory_settings["memory_win_default_levels"] = {380 "memory" : ( 80.0, 90.0 ),381 "pagefile" : ( 80.0, 90.0 ),382}383def inventory_mem_win(info):384 meminfo = parse_proc_meminfo(info)385 if "MemTotal" in meminfo and "PageTotal" in meminfo:386 return [(None, {})]387def check_mem_windows(item, params, info):388 meminfo = parse_proc_meminfo(info)389 MB = 1024.0 * 1024390 now = time.time()391 for title, what, paramname in [392 ( "Memory", "Mem", "memory" ),393 ( "Page file", "Page", "pagefile" )]:394 total_kb = meminfo[what + "Total"]395 free_kb = meminfo[what + "Free"]396 used_kb = total_kb - free_kb397 used_mb = used_kb / 1024.0398 free_mb = free_kb / 1024.0399 perc = 100.0 * used_kb / total_kb400 infotext = "%s usage: %.1f%% (%.1f/%.1f GB)" % \401 (title, perc, used_kb / MB, total_kb / MB)402 if type(params[paramname]) == tuple:403 warn, crit = params[paramname]404 # In perfdata show warn/crit as absolute values405 if type(warn) == float:406 warn_kb = total_kb * warn / 100 / 1024407 else:408 warn_kb = warn * 1024409 if type(crit) == float:410 crit_kb = total_kb * crit / 100 / 1024411 else:412 crit_kb = crit * 1024413 perfdata = [(paramname, used_kb / 1024.0, warn_kb, crit_kb, 0, total_kb / 1024.0)]414 # Predictive levels have no level information in the performance data415 else:416 perfdata = [(paramname, used_kb / 1024.0, None, None, 0, total_kb / 1024.0)]417 # Do averaging, if configured, just for matching the levels418 if "average" in params:419 average_min = params["average"]420 used_kb = get_average("mem.win.%s" % paramname,421 now, used_kb, average_min, initialize_zero = False)422 used_mb = used_kb / 1024.0423 free_mb = (total_kb / 1024.0) - used_mb424 perc = 100.0 * used_kb / total_kb425 infotext += ", %d min average: %.1f%% (%.1f GB)" % (average_min, perc, used_kb / MB)426 perfdata.append((paramname + "_avg", used_kb / 1024.0))427 # Now check the levels428 if type(params[paramname]) == tuple:429 if (type(crit) == int and free_mb <= crit) or \430 (type(crit) == float and perc >= crit):431 state = 2432 elif (type(warn) == int and free_mb <= warn) or \433 (type(warn) == float and perc >= warn):434 state = 1435 else:436 state = 0437 # Predictive levels438 else:439 state, infoadd, perfadd = check_levels(440 used_kb / 1024.0, # Current value stored in MB in RRDs441 "average" in params and paramname + "_avg" or paramname, # Name of RRD variable442 params[paramname],443 unit = "GB", # Levels are specified in GB...444 scale = 1024, # ... in WATO ValueSpec445 )446 if infoadd:447 infotext += ", " + infoadd448 perfdata += perfadd449 yield state, infotext, perfdata450check_info["mem.win"] = {451 'check_function': check_mem_windows,452 'inventory_function': inventory_mem_win,453 'service_description': 'Memory and pagefile',454 'has_perfdata': True,455 'group': 'memory_pagefile_win',456 'default_levels_variable': 'memory_win_default_levels',457}458#.459# .--mem.vmalloc---------------------------------------------------------.460# | _ _ |461# | _ __ ___ ___ _ __ ___ __ ___ __ ___ __ _| | | ___ ___ |462# | | '_ ` _ \ / _ \ '_ ` _ \\ \ / / '_ ` _ \ / _` | | |/ _ \ / __| |463# | | | | | | | __/ | | | | |\ V /| | | | | | (_| | | | (_) | (__ |464# | |_| |_| |_|\___|_| |_| |_(_)_/ |_| |_| |_|\__,_|_|_|\___/ \___| |465# | |466# +----------------------------------------------------------------------+467# | This very specific check checks the usage and fragmentation of the |468# | address space 'vmalloc' that can be problematic on 32-Bit systems. |469# | It is superseeded by the new check mem.linux and will be removed |470# | soon. |471# '----------------------------------------------------------------------'472# warn, crit, warn_chunk, crit_chunk. Integers are in MB, floats are in percent473mem_vmalloc_default_levels = ( 80.0, 90.0, 64, 32 )474def inventory_mem_vmalloc(info):475 meminfo = parse_proc_meminfo(info)476 if is_linux_meminfo(meminfo):477 return # handled by new Linux memory check478 if "VmallocTotal" in meminfo:479 # Do not checks this on 64 Bit systems. They have almost480 # infinitive vmalloc481 vmalloc = meminfo["VmallocTotal"] / 1024.4482 if vmalloc < 4096:483 return [ (None, "mem_vmalloc_default_levels") ]484def check_mem_vmalloc(item, params, info):485 meminfo = parse_proc_meminfo(info)486 total_mb = meminfo["VmallocTotal"] / 1024.0487 used_mb = meminfo["VmallocUsed"] / 1024.0488 free_mb = total_mb - used_mb489 chunk_mb = meminfo["VmallocChunk"] / 1024.0490 warn, crit, warn_chunk, crit_chunk = params491 state = 0492 infotxts = []493 perfdata = []494 for var, w, c, v, neg, what in [495 ( "used", warn, crit, used_mb, False, "used" ),496 ( "chunk", warn_chunk, crit_chunk, chunk_mb, True, "largest chunk" )]:497 # convert levels from percentage to MB values498 if type(w) == float:499 w_mb = total_mb * w / 100...
meminfo.py
Source:meminfo.py
...17 è¿åå表,æ¯ä¸ªåæ°é½æ¯tuple(memory,package_name,pid)18 Returns:19 ææè¿ç¨çpsså
å20 """21 meminfo = meminfo or self.get_system_meminfo()22 if m := self._parse_system_meminfo(meminfo):23 ret = []24 pss_by_process = m.group('pss_by_process').strip()25 pss_by_process = pss_by_process.splitlines()26 pattern = re.compile(r'(?P<memory>\S+K): (?P<name>\S+)\s*\(pid (?P<pid>\d+)')27 for process in pss_by_process:28 m = pattern.search(process.strip())29 memory, name, pid = self._pares_memory(m.group('memory')), m.group('name'), int(m.group('pid'))30 ret.append((memory, name, pid))31 return ret32 def get_total_ram(self, meminfo: Optional[str] = None) -> int:33 """34 è·åå
¨é¨å
å(total_ram)大å°,åä½(KB)35 Args:36 meminfo: å
åä¿¡æ¯37 Returns:38 å
å大å°(KB)39 """40 meminfo = meminfo or self.get_system_meminfo()41 if m := self._parse_system_meminfo(meminfo):42 return self._pares_memory(m.group('total_ram'))43 def get_free_ram(self, meminfo: Optional[str] = None) -> int:44 """45 è·åFree RAM大å°,åä½(KB)46 Args:47 meminfo: å
åä¿¡æ¯48 Returns:49 Free RAM(KB)50 """51 meminfo = meminfo or self.get_system_meminfo()52 if m := self._parse_system_meminfo(meminfo):53 return self._pares_memory(m.group('free_ram'))54 def get_used_ram(self, meminfo: Optional[str] = None) -> int:55 """56 è·åUsed RAM大å°,åä½(KB)57 Args:58 meminfo: å
åä¿¡æ¯59 Returns:60 Used RAM(KB)61 """62 meminfo = meminfo or self.get_system_meminfo()63 if m := self._parse_system_meminfo(meminfo):64 return self._pares_memory(m.group('used_ram'))65 def get_lost_ram(self, meminfo: Optional[str] = None) -> int:66 """67 è·åLost RAM大å°,åä½(KB)68 Args:69 meminfo: å
åä¿¡æ¯70 Returns:71 Lost RAM(KB)72 """73 meminfo = meminfo or self.get_system_meminfo()74 if m := self._parse_system_meminfo(meminfo):75 return self._pares_memory(m.group('lost_ram'))76 def get_app_meminfo(self, package: Union[str, int]) -> Optional[Dict[str, Dict[str, int]]]:77 """78 è·åæå®å
æè¿ç¨å·çå
åä¿¡æ¯79 é®ä¸ºå
åæ¡ç®å称80 å¼æ¯ä¸ä¸ªå
å«pss_total/private_dirty/private_clean/swapPss_dirty/heap_size/heap_alloc/heap_freeçåå
¸,对åºçå
åå ç¨(KB)81 Args:82 package: å
åæpidè¿ç¨å·83 Returns:84 以åå
¸è¿åææå
åä¿¡æ¯85 """86 if not package:87 return None88 ret = {}89 _memory_info_count = 790 if meminfo := self._get_app_meminfo(package):91 meminfo = self._parse_app_meminfo(meminfo)92 meminfo = meminfo.group('meminfo').strip()93 meminfo = meminfo.splitlines()94 # get meminfo head95 head_pattern = re.compile(r'(\S+)')96 headLine = [f'{t_1.lower()}_{t_2.lower()}' for t_1, t_2 in97 zip(head_pattern.findall(meminfo[0].strip()), head_pattern.findall(meminfo[1].strip()))]98 pattern = re.compile(r'\s*(\S+\s?\S*)\s*(.*)\r?')99 for line in meminfo[3:]:100 line = pattern.search(line)101 if not line:102 continue103 mem_pattern = re.compile(r'(\d+)\s*')104 mem = mem_pattern.findall(line.group(2).strip())105 # å°æ å
åä¿¡æ¯ç,è¡¥å
¨0106 mem += [0 for _ in range(_memory_info_count - len(mem))]107 name = line.group(1).strip().lower().replace(' ', '_')108 ret[name] = {headLine[index]: v for index, v in enumerate([int(v) for v in mem])}109 return ret110 def get_app_summary(self, package: Union[str, int]) -> Optional[Dict[str, int]]:111 """112 è·åapp summary pssã113 è¿åä¸ä¸ªå
å«java_heap/native_heap/code/stack/graphics/private_other/system/total/total_swap_pssçåå
¸114 Args:115 package: å
åæpidè¿ç¨å·116 Returns:117 appå
åä¿¡æ¯æ¦è¦118 """119 if not package:120 return None121 ret = {}122 if meminfo := self._get_app_meminfo(package):123 meminfo = self._parse_app_meminfo(meminfo)124 meminfo = meminfo.group('app_summary').strip()125 pattern = re.compile(r'\s*(\S+\s?\S*\s?\S*):\s*(\d+)')126 for v in pattern.findall(meminfo):127 name = v[0].strip().lower().replace(' ', '_')128 memory = int(v[1])129 ret[name] = memory130 return ret131 @staticmethod132 def _pares_memory(memory: str):133 """134 å¤çå符串memory,转æ¢ä¸ºint,åä½KB135 Args:136 memory(str): å
å137 Returns:138 å
å大å°,åä½(KB)139 """140 memory = int(memory.strip().replace(',', '').replace('K', ''))141 return memory142 @staticmethod143 def _parse_system_meminfo(meminfo: str) -> Optional[Match[str]]:144 """145 å¤çadb shell dumpsys meminfoè¿åçæ°æ®146 Args:147 meminfo: å
åæ°æ®148 Returns:149 å
å«uptimeãrealtimeãpss_by_processãpss_by_ommAdjustemntãpss_by_categoryã150 total_ramãfree_ramãused_ramãlost_ram151 """152 pattern = re.compile(r'Uptime: (?P<uptime>\d+) Realtime: (?P<realtime>\d+)'153 r'.*Total PSS by process:(?P<pss_by_process>.*)'154 r'.*Total PSS by OOM adjustment:(?P<pss_by_ommAdjustemnt>.*)'155 r'.*Total PSS by category:(?P<pss_by_category>.*)'156 r'.*Total RAM:\s*(?P<total_ram>\S+)'157 r'.*Free RAM:\s*(?P<free_ram>\S+)'158 r'.*Used RAM:\s*(?P<used_ram>\S+)'159 r'.*Lost RAM:\s*(?P<lost_ram>\S+)', re.DOTALL)160 return m if (m := pattern.search(meminfo)) else None161 @staticmethod162 def _parse_app_meminfo(meminfo: str):163 pattern = re.compile(r'Uptime: (?P<uptime>\d+) Realtime: (?P<realtime>\d+)'164 r'.*\*\* MEMINFO in pid (?P<pid>\d+) \[(?P<package_name>\S+)] \*\*'165 r'(?P<meminfo>.*)'166 r'.*App Summary\s*(?P<app_summary>.*)'167 r'.*Objects(.*)', re.DOTALL)168 return m if (m := pattern.search(meminfo)) else None169 def _get_app_meminfo(self, packageName: Union[str, int]):170 """171 'adb shell dumpsys meminfo <packageName|pid>' è·åæå®å
æè¿ç¨å·çå
åä¿¡æ¯172 Raises:173 AdbProcessNotFound: æªæ¾å°å¯¹åºè¿ç¨æ¶å¼¹åºå¼å¸¸174 Args:175 packageName: å
åæpidè¿ç¨å·176 Returns:177 å
åä¿¡æ¯178 """179 if isinstance(packageName, int):180 arg = packageName181 else:182 arg = self.device.get_pid_by_name(packageName=packageName)183 if not arg:184 raise AdbProcessNotFound(f"'{packageName}' not found")185 arg = str(arg[0][0])186 if 'No process found for:' in (ret := self.device.shell(['dumpsys', 'meminfo', arg])):187 raise AdbProcessNotFound(ret.strip())188 else:189 return ret190 def get_system_meminfo(self) -> str:191 """192 'adb shell dumpsys meminfo' è·åç³»ç»å
åä¿¡æ¯193 Returns:194 å
åä¿¡æ¯195 """196 return self.device.shell(['dumpsys', 'meminfo'])197if __name__ == '__main__':198 from adbutils import ADBDevice199 from adbutils.extra.performance.meminfo import Meminfo200 device = ADBDevice(device_id='')201 performance = Meminfo(device)202 performance.get_system_meminfo()203 for i in range(100):204 package_name = device.foreground_package205 total = performance.get_app_summary(package_name)['total']206 # æå°package_name对åºappçå
åå ç¨...
mem.py
Source:mem.py
1#!/usr/bin/env python2import os3def meminfo2dict():4 if not os.path.exists('/proc/meminfo'):5 return None6 f = open('/proc/meminfo', 'r')7 lines = f.readlines()8 f.close()9 info = {}10 for line in lines:11 line = line[:-1]12 parts = line.split(':')13 key = parts[0]14 value = parts[1].strip()15 value = value.split()16 value = int(value[0])17 info[key] = value18 return info19def stats(meminfo=meminfo2dict()):20 if meminfo is None:21 return22 total = meminfo['MemTotal']23 free = meminfo['MemFree']24 used = total - free25 buffers = meminfo['Buffers']26 cached = meminfo['Cached']27 used2 = used - buffers - cached28 free2 = free + buffers + cached29 swaptotal = meminfo['SwapTotal']30 swapfree = meminfo['SwapFree']31 swapused = swaptotal - swapfree32 print '%10d%10d%10d%10d%10d' % (total, used, free, buffers, cached)33 print '%20d%10d' % (used2, free2)34 print '%10d%10d%10d' % (swaptotal, swapused, swapfree)35 meminfo36def used():37 meminfo = meminfo2dict()38 used = meminfo['MemTotal'] - meminfo['MemFree']39 return used40def active():41 return 042 meminfo = meminfo2dict()43 used = meminfo['MemTotal'] - meminfo['MemFree'] - meminfo['Cached']44 return used45def free():46 meminfo = meminfo2dict()47 free = meminfo['MemFree'] + meminfo['Cached']48 return free49def total():50 meminfo = meminfo2dict()51 total = meminfo['MemTotal']52 return total53def swapused():54 meminfo = meminfo2dict()55 used = meminfo['SwapTotal'] - meminfo['SwapFree']56 return used57def swapfree():58 meminfo = meminfo2dict()59 free = meminfo['SwapFree']60 return free61def swaptotal():62 meminfo = meminfo2dict()63 total = meminfo['SwapTotal']64 return total65multdict = {66 'b': 1,67 'kb': 1024,68 'mb': 1024*1024,69 'gb': 1024*1024*1024,70}71def procStatus(pid=None):72 if pid is None:73 pid = os.getpid()74 f = open('/proc/%d/status' % (pid,))75 statuslines = f.readlines()76 f.close()77 vm = {}78 for statusline in statuslines:79 fields = statusline.split()80 if fields[0][:2] == 'Vm':81 name = fields[0][:-1]82 value = int(fields[1])83 mult = multdict[fields[2].lower()]84 vm[name] = mult*value85 return vm86def mySize():87 status = procStatus()88 return status['VmRSS']89def test():90 mypid = os.getpid()91 print 'mypid', mypid92 print mySize()93if __name__ == '__main__':94 #print used()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!