Best Python code snippet using fMBT_python
cs50.py
Source: cs50.py
...12# Prevent flask, werkzeug, etc from adding default handler13logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.DEBUG)14try:15 # Patch formatException16 logging.root.handlers[0].formatter.formatException = lambda exc_info: _formatException(*exc_info)17except IndexError:18 pass19# Configure cs50 logger20_logger = logging.getLogger("cs50")21_logger.setLevel(logging.DEBUG)22# Log messages once23_logger.propagate = False24handler = logging.StreamHandler()25handler.setLevel(logging.DEBUG)26formatter = logging.Formatter("%(levelname)s: %(message)s")27formatter.formatException = lambda exc_info: _formatException(*exc_info)28handler.setFormatter(formatter)29_logger.addHandler(handler)30class _flushfile():31 """32 Disable buffering for standard output and standard error.33 http://stackoverflow.com/a/23121634 """35 def __init__(self, f):36 self.f = f37 def __getattr__(self, name):38 return object.__getattribute__(self.f, name)39 def write(self, x):40 self.f.write(x)41 self.f.flush()42sys.stderr = _flushfile(sys.stderr)43sys.stdout = _flushfile(sys.stdout)44def _formatException(type, value, tb):45 """46 Format traceback, darkening entries from global site-packages directories47 and user-specific site-packages directory.48 https://stackoverflow.com/a/46071447/515619049 """50 # Absolute paths to site-packages51 packages = tuple(join(abspath(p), "") for p in sys.path[1:])52 # Highlight lines not referring to files in site-packages53 lines = []54 for line in format_exception(type, value, tb):55 matches = re.search(r"^ File \"([^\"]+)\", line \d+, in .+", line)56 if matches and matches.group(1).startswith(packages):57 lines += line58 else:59 matches = re.search(r"^(\s*)(.*?)(\s*)$", line, re.DOTALL)60 lines.append(matches.group(1) + colored(matches.group(2), "yellow") + matches.group(3))61 return "".join(lines).rstrip()62sys.excepthook = lambda type, value, tb: print(_formatException(type, value, tb), file=sys.stderr)63def eprint(*args, **kwargs):64 raise RuntimeError("The CS50 Library for Python no longer supports eprint, but you can use print instead!")65def get_char(prompt):66 raise RuntimeError("The CS50 Library for Python no longer supports get_char, but you can use get_string instead!")67def get_float(prompt):68 """69 Read a line of text from standard input and return the equivalent float70 as precisely as possible; if text does not represent a double, user is71 prompted to retry. If line can't be read, return None.72 """73 while True:74 s = get_string(prompt)75 if s is None:76 return None...
Formatter.py
Source: Formatter.py
...35 self._fmt = fmt36 self._exceptionfmt = exceptionfmt37 def formatException(self, exc_info):38 return ""39 def _formatException(self, exc_info):40 return self._exceptionfmt % { 41 "classname": exc_info[0].__module__ + "." + exc_info[0].__name__,42 "message": exc_info[1],43 "traceback": "".join(format_tb(exc_info[2])).rstrip()44 }45 def format(self, record):46 if not(record.exc_info is None) and self.formatStackTrace:47 return super(SimpleFormatter, self).format(record).rstrip() + "\n" + self._formatException(record.exc_info).rstrip()48 #return self._formatException(record.exc_info).rstrip() + "\n" + super(SimpleFormatter, self).format(record)49 else:50 return super(SimpleFormatter, self).format(record)51class ColoredFormatter(logging.Formatter):52 datefmt = "%Y-%m-%d %H:%M:%S"53 _fmt = None54 _exceptionfmt = None55 useColors = True56 formatStackTrace = False57 def __init__(self, fmt=None, datefmt="%Y-%m-%d %H:%M:%S", exceptionfmt="Traceback (most recent call last):\n%(traceback)s\n%(classname)s: %(message)s"):58 # set standard Formatter values59 self.datefmt = datefmt60 self._fmt = fmt61 self._exceptionfmt = exceptionfmt62 # set colors63 self._fmt = Template(fmt).safe_substitute(SHELL_COLORS)64 self._exceptionfmt = Template(exceptionfmt).safe_substitute(SHELL_COLORS)65 # do we have a tty?66 if sys.stdout.isatty() or os.isatty(sys.stdout.fileno()):67 self.useColors = True68 else:69 self.useColors = False70 # remove all colors71 if not self.useColors:72 self._fmt = re.sub("\033\[(\d+|;)+m", "", self._fmt)73 self._exceptionfmt = re.sub("\033\[(\d+|;)+m", "", self._exceptionfmt)74 def formatException(self, exc_info):75 return ""76 def _formatException(self, exc_info):77 return self._exceptionfmt % { 78 "classname": exc_info[0].__module__ + "." + exc_info[0].__name__,79 "message": exc_info[1],80 "traceback": "".join(format_tb(exc_info[2])).rstrip()81 }82 def format(self, record):83 fmt = self._fmt84 try:85 if self.useColors:86 self._fmt = Template(fmt).safe_substitute({ "color_level": LOG_LEVEL_COLORS[record.levelname.upper()] })87 else:88 self._fmt = Template(fmt).safe_substitute({ "color_level": "" })89 if not(record.exc_info is None) and self.formatStackTrace:90 return super(ColoredFormatter, self).format(record).rstrip() + "\n" + self._formatException(record.exc_info).rstrip()91 #return self._formatException(record.exc_info).rstrip() + "\n" + super(ColoredFormatter, self).format(record)92 else:93 return super(ColoredFormatter, self).format(record)94 finally:...
Check out the latest blogs from LambdaTest on this topic:
Collecting and examining data from multiple sources can be a tedious process. The digital world is constantly evolving. To stay competitive in this fast-paced environment, businesses must frequently test their products and services. While it’s easy to collect raw data from multiple sources, it’s far more complex to interpret it properly.
Hola Testers! Hope you all had a great Thanksgiving weekend! To make this time more memorable, we at LambdaTest have something to offer you as a token of appreciation.
When I started writing tests with Cypress, I was always going to use the user interface to interact and change the application’s state when running tests.
So, now that the first installment of this two fold article has been published (hence you might have an idea of what Agile Testing is not in my opinion), I’ve started feeling the pressure to explain what Agile Testing actually means to me.
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!!