Best Python code snippet using pyresttest_python
procinfo.py
Source:procinfo.py
...115 if n >= prefix[s]:116 value = float(n) / prefix[s]117 return '%.1f%s' % (value, s)118 return "%sB" % n119def print_(a, b):120 if sys.stdout.isatty() and psutil.POSIX:121 fmt = '\x1b[1;32m%-13s\x1b[0m %s' % (a, b)122 else:123 fmt = '%-11s %s' % (a, b)124 print(fmt)125def str_ntuple(nt, bytes2human=False):126 if nt == ACCESS_DENIED:127 return ""128 if not bytes2human:129 return ", ".join(["%s=%s" % (x, getattr(nt, x)) for x in nt._fields])130 else:131 return ", ".join(["%s=%s" % (x, convert_bytes(getattr(nt, x)))132 for x in nt._fields])133def run(pid, verbose=False):134 try:135 proc = psutil.Process(pid)136 pinfo = proc.as_dict(ad_value=ACCESS_DENIED)137 except psutil.NoSuchProcess as err:138 sys.exit(str(err))139 # collect other proc info140 with proc.oneshot():141 try:142 parent = proc.parent()143 if parent:144 parent = '(%s)' % parent.name()145 else:146 parent = ''147 except psutil.Error:148 parent = ''149 try:150 pinfo['children'] = proc.children()151 except psutil.Error:152 pinfo['children'] = []153 if pinfo['create_time']:154 started = datetime.datetime.fromtimestamp(155 pinfo['create_time']).strftime('%Y-%m-%d %H:%M')156 else:157 started = ACCESS_DENIED158 # here we go159 print_('pid', pinfo['pid'])160 print_('name', pinfo['name'])161 print_('parent', '%s %s' % (pinfo['ppid'], parent))162 print_('exe', pinfo['exe'])163 print_('cwd', pinfo['cwd'])164 print_('cmdline', ' '.join(pinfo['cmdline']))165 print_('started', started)166 cpu_tot_time = datetime.timedelta(seconds=sum(pinfo['cpu_times']))167 cpu_tot_time = "%s:%s.%s" % (168 cpu_tot_time.seconds // 60 % 60,169 str((cpu_tot_time.seconds % 60)).zfill(2),170 str(cpu_tot_time.microseconds)[:2])171 print_('cpu-tspent', cpu_tot_time)172 print_('cpu-times', str_ntuple(pinfo['cpu_times']))173 if hasattr(proc, "cpu_affinity"):174 print_("cpu-affinity", pinfo["cpu_affinity"])175 print_('memory', str_ntuple(pinfo['memory_info'], bytes2human=True))176 print_('memory %', round(pinfo['memory_percent'], 2))177 print_('user', pinfo['username'])178 if psutil.POSIX:179 print_('uids', str_ntuple(pinfo['uids']))180 if psutil.POSIX:181 print_('uids', str_ntuple(pinfo['uids']))182 if psutil.POSIX:183 print_('terminal', pinfo['terminal'] or '')184 print_('status', pinfo['status'])185 print_('nice', pinfo['nice'])186 if hasattr(proc, "ionice"):187 try:188 ionice = proc.ionice()189 except psutil.Error:190 pass191 else:192 if psutil.WINDOWS:193 print_("ionice", ionice)194 else:195 print_("ionice", "class=%s, value=%s" % (196 str(ionice.ioclass), ionice.value))197 print_('num-threads', pinfo['num_threads'])198 if psutil.POSIX:199 print_('num-fds', pinfo['num_fds'])200 if psutil.WINDOWS:201 print_('num-handles', pinfo['num_handles'])202 if 'io_counters' in pinfo:203 print_('I/O', str_ntuple(pinfo['io_counters'], bytes2human=True))204 print_("ctx-switches", str_ntuple(pinfo['num_ctx_switches']))205 if pinfo['children']:206 template = "%-6s %s"207 print_("children", template % ("PID", "NAME"))208 for child in pinfo['children']:209 try:210 print_('', template % (child.pid, child.name()))211 except psutil.AccessDenied:212 print_('', template % (child.pid, ""))213 except psutil.NoSuchProcess:214 pass215 if pinfo['open_files']:216 print_('open-files', 'PATH')217 for i, file in enumerate(pinfo['open_files']):218 if not verbose and i >= NON_VERBOSE_ITERATIONS:219 print_("", "[...]")220 break221 print_('', file.path)222 else:223 print_('open-files', '')224 if pinfo['connections']:225 template = '%-5s %-25s %-25s %s'226 print_('connections',227 template % ('PROTO', 'LOCAL ADDR', 'REMOTE ADDR', 'STATUS'))228 for conn in pinfo['connections']:229 if conn.type == socket.SOCK_STREAM:230 type = 'TCP'231 elif conn.type == socket.SOCK_DGRAM:232 type = 'UDP'233 else:234 type = 'UNIX'235 lip, lport = conn.laddr236 if not conn.raddr:237 rip, rport = '*', '*'238 else:239 rip, rport = conn.raddr240 print_('', template % (241 type,242 "%s:%s" % (lip, lport),243 "%s:%s" % (rip, rport),244 conn.status))245 else:246 print_('connections', '')247 if pinfo['threads'] and len(pinfo['threads']) > 1:248 template = "%-5s %12s %12s"249 print_('threads', template % ("TID", "USER", "SYSTEM"))250 for i, thread in enumerate(pinfo['threads']):251 if not verbose and i >= NON_VERBOSE_ITERATIONS:252 print_("", "[...]")253 break254 print_('', template % thread)255 print_('', "total=%s" % len(pinfo['threads']))256 else:257 print_('threads', '')258 if hasattr(proc, "rlimit"):259 res_names = [x for x in dir(psutil) if x.startswith("RLIMIT")]260 resources = []261 for res_name in res_names:262 try:263 soft, hard = proc.rlimit(getattr(psutil, res_name))264 except psutil.AccessDenied:265 pass266 else:267 resources.append((res_name, soft, hard))268 if resources:269 template = "%-12s %15s %15s"270 print_("res-limits", template % ("RLIMIT", "SOFT", "HARD"))271 for res_name, soft, hard in resources:272 if soft == psutil.RLIM_INFINITY:273 soft = "infinity"274 if hard == psutil.RLIM_INFINITY:275 hard = "infinity"276 print_('', template % (277 RLIMITS_MAP.get(res_name, res_name), soft, hard))278 if hasattr(proc, "environ") and pinfo['environ']:279 template = "%-25s %s"280 print_("environ", template % ("NAME", "VALUE"))281 for i, k in enumerate(sorted(pinfo['environ'])):282 if not verbose and i >= NON_VERBOSE_ITERATIONS:283 print_("", "[...]")284 break285 print_("", template % (k, pinfo['environ'][k]))286 if pinfo.get('memory_maps', None):287 template = "%-8s %s"288 print_("mem-maps", template % ("RSS", "PATH"))289 maps = sorted(pinfo['memory_maps'], key=lambda x: x.rss, reverse=True)290 for i, region in enumerate(maps):291 if not verbose and i >= NON_VERBOSE_ITERATIONS:292 print_("", "[...]")293 break294 print_("", template % (convert_bytes(region.rss), region.path))295def main(argv=None):296 parser = argparse.ArgumentParser(297 description="print information about a process")298 parser.add_argument("pid", type=int, help="process pid")299 parser.add_argument('--verbose', '-v', action='store_true',300 help="print more info")301 args = parser.parse_args()302 run(args.pid, args.verbose)303if __name__ == '__main__':...
test_print.py
Source:test_print.py
...7 self.level = 08 self.lines = []9 def __str__(self):10 return "\n".join(self.lines)11 def print_(self, txt):12 self.lines.append(" " * self.level + txt)13 def module_class(self, c):14 self.print_("class:")15 self.level += 116 self.print_("name: %s" % c.name)17 if c.base_name:18 self.print_("base_name: %s" % c.base_name.get())19 if c.stats:20 self.stats(c.stats.get())21 self.level -= 122 def module_enum(self, e):23 self.print_("enum:")24 self.level += 125 self.print_("name: %s" % e.name)26 self.print_("base_name: %s" % e.base_name)27 if e.stats:28 self.enum_stats(e.stats.get())29 self.level -= 130 def stats(self, s):31 self.print_("stats:")32 self.level += 133 formast.Visitor.stats(self, s)34 self.level -= 135 def stats_field(self, a):36 self.print_("field:")37 self.level += 138 self.print_("type: %s" % a.type_)39 self.print_("name: %s" % a.name)40 self.level -= 141 def stats_if(self, if_):42 self.print_("if:")43 self.level += 144 self.expr(if_.expr)45 self.print_("then:")46 self.level += 147 self.stats(if_.then)48 self.level -= 149 if if_.else_:50 self.print_("else:")51 self.level += 152 self.stats(if_.else_.get())53 self.level -= 154 self.level -= 155 def enum_stats(self, s):56 self.print_("stats:")57 self.level += 158 formast.Visitor.enum_stats(self, s)59 self.level -= 160 def enum_stats_const(self, c):61 self.print_("const:")62 self.level += 163 self.print_("name: %s" % c.name)64 self.print_("value: %s" % c.value)65 self.level -= 166 def expr_uint(self, v):67 self.print_("uint: %s" % v)68 def expr_id(self, i):69 self.print_("id: %s" % i)70 def expr_pos(self, right):71 self.print_("pos:")72 self.level += 173 self.expr(right)74 self.level -= 175 def expr_neg(self, right):76 self.print_("neg:")77 self.level += 178 self.expr(right)79 self.level -= 180 def expr_add(self, left, right):81 self.print_("add:")82 self.level += 183 self.expr(left)84 self.expr(right)85 self.level -= 186 def expr_sub(self, left, right):87 self.print_("sub:")88 self.level += 189 self.expr(left)90 self.expr(right)91 self.level -= 192 def expr_mul(self, left, right):93 self.print_("mul:")94 self.level += 195 self.expr(left)96 self.expr(right)97 self.level -= 198 def expr_div(self, left, right):99 self.print_("div:")100 self.level += 1101 self.expr(left)102 self.expr(right)103 self.level -= 1104 def expr_mod(self, left, right):105 self.print_("mod:")106 self.level += 1107 self.expr(left)108 self.expr(right)109 self.level -= 1110 def expr_pow(self, left, right):111 self.print_("pow:")112 self.level += 1113 self.expr(left)114 self.expr(right)115 self.level -= 1116 def expr_logical_and(self, left, right):117 self.print_("logical_and:")118 self.level += 1119 self.expr(left)120 self.expr(right)121 self.level -= 1122 def expr_logical_or(self, left, right):123 self.print_("logical_or:")124 self.level += 1125 self.expr(left)126 self.expr(right)127 self.level -= 1128 def expr_logical_not(self, right):129 self.print_("not:")130 self.level += 1131 self.expr(right)132 self.level -= 1133 def expr_bitwise_and(self, left, right):134 self.print_("bitwise_and:")135 self.level += 1136 self.expr(left)137 self.expr(right)138 self.level -= 1139 def expr_bitwise_or(self, left, right):140 self.print_("bitwise_or:")141 self.level += 1142 self.expr(left)143 self.expr(right)144 self.level -= 1145 def expr_bitwise_xor(self, left, right):146 self.print_("bitwise_xor:")147 self.level += 1148 self.expr(left)149 self.expr(right)150 self.level -= 1151 def expr_compare_eq(self, left, right):152 self.print_("compare_eq:")153 self.level += 1154 self.expr(left)155 self.expr(right)156 self.level -= 1157 def expr_compare_ne(self, left, right):158 self.print_("compare_ne:")159 self.level += 1160 self.expr(left)161 self.expr(right)162 self.level -= 1163 def expr_compare_gt(self, left, right):164 self.print_("compare_gt:")165 self.level += 1166 self.expr(left)167 self.expr(right)168 self.level -= 1169 def expr_compare_lt(self, left, right):170 self.print_("compare_lt:")171 self.level += 1172 self.expr(left)173 self.expr(right)174 self.level -= 1175 def expr_compare_ge(self, left, right):176 self.print_("compare_ge:")177 self.level += 1178 self.expr(left)179 self.expr(right)180 self.level -= 1181 def expr_compare_le(self, left, right):182 self.print_("compare_le:")183 self.level += 1184 self.expr(left)185 self.expr(right)186 self.level -= 1187 def expr_shift_left(self, left, right):188 self.print_("shift_left:")189 self.level += 1190 self.expr(left)191 self.expr(right)192 self.level -= 1193 def expr_shift_right(self, left, right):194 self.print_("shift_right:")195 self.level += 1196 self.expr(left)197 self.expr(right)198 self.level -= 1199class TestPrint:200 def setup(self):201 self.parser = formast.XmlParser()202 self.printer = Printer()203 def check(self, inp , out):204 module = formast.Module()205 self.parser.parse_string(self.make_input_from_cond(inp), module)206 self.printer.module(module)207 nose.tools.assert_equal(str(self.printer), out)208 def make_input_from_cond(self, cond):...
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!!