How to use prepend_timestamp method in autotest

Best Python code snippet using autotest_python

Base.py

Source:Base.py Github

copy

Full Screen

1#!/usr/bin/python32from pathlib import Path3import time, datetime4import numpy as np5# Base6########################################7class Base():8 9 def __init__(self, name='-', common=None, verbosity=3, log_verbosity=None):10 11 self.name = name12 self._common = common13 self.verbosity = verbosity14 self.log_verbosity = log_verbosity # None means we use the msg/print verbosity15 16 self.indent_depth = 017 # Verbosity meaning18 ################################################################################19 # verbosity=0 : Output nothing20 # verbosity=1 : Output only most important messages (e.g. errors)21 # verbosity=2 : Output 'regular' amounts of information/data22 # verbosity=3 : Output all useful results23 # verbosity=4 : Output marginally useful things (e.g. essentially redundant/obvious things)24 # verbosity=5 : Output everything (e.g. for testing)25 # Messages (print and log)26 ########################################27 def indent(self, indent=1):28 self.indent_depth += indent29 def dedent(self, dedent=1):30 self.indent_depth -= dedent31 32 def date_stamp(self, threshold=1, indent=0, verbosity=None, **kwargs):33 date_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")34 self.msg(date_str, threshold=threshold, indent=indent, verbosity=verbosity, **kwargs)35 36 37 def msg(self, txt, threshold=3, indent=0, indent_txt=' ', verbosity=None, empty_lines=0, raw=False, **kwargs):38 '''Outputs a status line indicating the current state of execution.'''39 if verbosity is None:40 verbosity = self.verbosity41 indent = np.clip(indent+self.indent_depth, 0, 10)42 indent = indent_txt*indent43 if raw:44 message = txt45 else:46 message = '{}> {}{}'.format(self.name, indent, txt)47 48 if verbosity>=threshold:49 for i in range(empty_lines):50 print('')51 print(message)52 if self.log_verbosity is None and self._common:53 for i in range(empty_lines):54 self._common.log('')55 self._common.log(message, threshold=threshold)56 57 if self.log_verbosity is not None and self.log_verbosity>=threshold and self._common:58 for i in range(empty_lines):59 self._common.log('')60 self._common.log(message, threshold=threshold)61 62 def msgm(self, txt=None, threshold=1, indent=0, verbosity=None, mark='=', nmark=40, empty_lines=1, **kwargs):63 '''Outputs a very noticeable message, demarcated by lines.'''64 65 self.msg(txt=mark*nmark, threshold=threshold, indent=indent, verbosity=verbosity, empty_lines=empty_lines, **kwargs)66 if txt is not None:67 self.msg(txt=txt, threshold=threshold, indent=indent, verbosity=verbosity, **kwargs)68 self.msg(txt=mark*nmark, threshold=threshold, indent=indent, verbosity=verbosity, **kwargs)69 def msg_warning(self, txt, threshold=2, indent=0, verbosity=None, empty_lines=1, **kwargs):70 txt = 'WARNING: {}'.format(txt)71 self.msgm(txt=txt, threshold=threshold, indent=indent, verbosity=verbosity, empty_lines=empty_lines, **kwargs)72 73 74 def msg_error(self, txt, threshold=1, indent=0, verbosity=None, empty_lines=1, **kwargs):75 txt = 'ERROR: {}'.format(txt)76 self.msgm(txt=txt, threshold=threshold, indent=indent, verbosity=verbosity, empty_lines=empty_lines, **kwargs)77 # Messages (timing)78 ########################################79 80 def timing_start(self):81 self.start_time = time.time()82 83 def timing_end(self):84 return time.time() - self.start_time85 86 87 def timing_end_msg(self, txt='', iterations=None, threshold=3, indent=0, indent_txt=' ', verbosity=None, empty_lines=0, **kwargs):88 took = self.timing_end()89 if iterations is None:90 txt = '{} took {:.1f}s'.format(txt, took)91 else:92 txt = '{} took {:.1f}s for {} iterations ({:.3f} s/iteration)'.format(txt, took, iterations, took/iterations)93 self.msg(txt, threshold=threshold, indent=indent, indent_txt=indent_txt, verbosity=verbosity, empty_lines=empty_lines, **kwargs)94 def timing_progress_msg(self, icurrent, itotal, threshold=4, indent=4, indent_txt=' ', every=50, verbosity=None):95 if verbosity is None:96 verbosity = self.verbosity97 if verbosity>=threshold:98 if icurrent%every==0:99 amt = icurrent/itotal100 took = self.timing_end()101 if icurrent>0 and icurrent<itotal:102 estimate = (itotal-icurrent)*took/icurrent103 estimate = '; done in ~{}'.format(self.time_diff_str(estimate))104 else:105 estimate = ''106 txt = "{}{:,d}/{:,d} = {:.1f}% ({}{})".format(indent_txt*indent, icurrent, itotal, 100.*icurrent/itotal, self.time_diff_str(took), estimate)107 self.print(txt)108 def now(self, str_format='%Y-%m-%d %H:%M:%S'):109 #return time.strftime(str_format)110 return datetime.datetime.now().strftime(str_format)111 def time_str(self, timestamp, str_format='%Y-%m-%d %H:%M:%S'):112 #time_tuple = time.gmtime(timestamp)113 #s = time.strftime(str_format, time_tuple)114 s = datetime.datetime.fromtimestamp(timestamp).strftime(str_format)115 return s116 def time_diff_str(self, diff):117 diff = abs(diff)118 if diff>60*60*48:119 diff = '{:.1f} days'.format(diff/(60*60*24))120 elif diff>60*60:121 diff = '{:.1f} hours'.format(diff/(60*60))122 elif diff>60:123 diff = '{:.1f} mins'.format(diff/60)124 elif diff>0.1:125 diff = '{:.1f} s'.format(diff)126 else:127 diff = '{:.4f} s'.format(diff)128 129 return diff130 def time_delta(self, first, second):131 diff = self.time_diff_str(second-first)132 133 if second<first:134 return '{} earlier'.format(diff)135 else:136 return '{} later'.format(diff)137 138 # Messages (data)139 ########################################140 def print(self, txt, **kwargs):141 self.msg(txt, threshold=1, raw=True, **kwargs)142 143 def print_array(self, data, name='array', verbosity=3):144 '''Helper code for inspecting arrays (e.g. for debugging).'''145 span = np.max(data)-np.min(data)146 if verbosity>=3:147 self.print('print_array for: {} (shape: {})'.format(name, data.shape))148 if verbosity>=1:149 self.print(' values: {:.4g} ± {:.4g} (span {:.3g}, from {:.3g} to {:.3g})'.format(np.average(data), np.std(data), span, np.min(data), np.max(data)))150 if verbosity>=4:151 self.print(data)152 def print_d(self, d, i=4):153 '''Simple helper to print a dictionary.'''154 for k, v in d.items():155 if isinstance(v,dict):156 self.print('{}{} : <dict>'.format(' '*i,k))157 self.print_d(v, i=i+4)158 elif isinstance(v,(np.ndarray)):159 self.print('{}{} : Ar{}: {}'.format(' '*i,k,v.shape,v))160 elif isinstance(v,(list,tuple)):161 self.print('{}{} : L{}: {}'.format(' '*i,k,len(v),v))162 else:163 self.print('{}{} : {}'.format(' '*i,k,v))164 def print_results(self, results):165 '''Simple helper to print out a list of dictionaries.'''166 for i, result in enumerate(results):167 self.print(i)168 self.print_d(result)169 def print_n(self, d):170 '''Simple helper to print nested arrays/dicts'''171 if isinstance(d, (list,tuple,np.ndarray)):172 self.print_results(d)173 elif isinstance(d, dict):174 self.print_d(d)175 else:176 self.print(d)177 def val_stats(self, values, name='z', sizing=False):178 span = np.max(values)-np.min(values)179 if sizing:180 sizing = " [{} = {} elements]".format(values.shape, values.size)181 else:182 sizing = ""183 self.print(" {} = {:.2g} ± {:.2g} (span {:.2g}, from {:.3g} to {:.3g}){}".format(name, np.average(values), np.std(values), span, np.min(values), np.max(values), sizing)) 184 185 186 # End class Base()187 ########################################188 189 190# Common191########################################192class Common():193 '''A class meant to hold settings and pointers to open files, which many194 different other classes/objects may need to access.'''195 196 def __init__(self, settings=None, logdir='./logs/', log_verbosity=None, prepend_timestamp=True):197 198 self.settings = {} if settings is None else settings199 200 self.logdir = logdir201 self.log_verbosity = log_verbosity202 self._logfile = None203 self.prepend_timestamp = prepend_timestamp204 self._accumulate = False205 self._accumulated_msgs = []206 def log(self, msg, prepend_timestamp=None, threshold=None):207 208 if (threshold is None) or (self.log_verbosity is None) or (self.log_verbosity>=threshold):209 if self._accumulate:210 self._accumulated_msgs.append(msg)211 212 logdir = Path(self.logdir)213 logfile = '{}.log'.format(datetime.datetime.now().strftime("%Y-%m-%d"))214 215 if self._logfile is None:216 # Open new logfile if none exists217 logdir.mkdir(exist_ok=True)218 logfile = Path(logdir, logfile)219 self._logfile = open(logfile, 'a', buffering=1)220 221 else:222 # Check if existing logfile is from yesterday223 cur_logfile = Path(self._logfile.name).name224 if cur_logfile!=logfile:225 logdir.mkdir(exist_ok=True)226 logfile = Path(logdir, logfile)227 self._logfile = open(logfile, 'a', buffering=1)228 229 230 if (prepend_timestamp is None and self.prepend_timestamp) or prepend_timestamp:231 timestamp = datetime.datetime.now().strftime("%Y-%m-%d (%a %b %d) %H:%M:%S")232 #timestamp = datetime.datetime.now().strftime("%H:%M:%S")233 msg = '[{}] {}'.format(timestamp, msg)234 235 self._logfile.write('{}\n'.format(msg))236 237 238 239 def accumulate_msgs(self):240 self._accumulate = True241 self._accumulated_msgs = []242 243 def get_accumulated_msgs(self):244 m = self._accumulated_msgs245 self._accumulate = False246 self._accumulated_msgs = []247 return m 248 249 250 def __del__(self):251 if self._logfile is not None:252 self._logfile.close()253 254 255 # End class Common()256 ########################################257 258 259# MotorAxes260class MotorAxes(Base):261 def __init__(self, name='axes', log_verbosity=5, **kwargs):262 super().__init__(name=name, log_verbosity=log_verbosity, **kwargs)263 264 # End class MotorAxes()...

Full Screen

Full Screen

apply_timestamp.py

Source:apply_timestamp.py Github

copy

Full Screen

2Prepend a timestamp to stdin stream messages3"""4import sys5import datetime6def prepend_timestamp(stdin_message):7 return f"[{datetime.datetime.now()}] {stdin_message}"8if __name__ == "__main__":9 for line in sys.stdin:10 line = prepend_timestamp(line)11 sys.stdout.write(line)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful