def noinject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=0, via=None): """ Use in modules that do not have inject in them Does not inject anything into the module. Just lets utool know that a module is being imported so the import order can be debuged """ if PRINT_INJECT_ORDER: from utool._internal import meta_util_dbg callername = meta_util_dbg.get_caller_name(N=N + 1, strict=False) lineno = meta_util_dbg.get_caller_lineno(N=N + 1, strict=False) suff = ' via %s' % (via, ) if via else '' fmtdict = dict(N=N, lineno=lineno, callername=callername, modname=module_name, suff=suff) msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}{suff}'.format( **fmtdict) builtins.print(msg) if EXIT_ON_INJECT_MODNAME == module_name: builtins.print('...exiting') assert False, 'exit in inject requested'
def _print(*objects, **kwargs): """ Overload the print function to adapt for the encoding bug in Windows console. It will try to convert text to the console encoding before printing to prevent crashes. """ try: stream = kwargs.get('file', None) if stream is None: stream = sys.stdout enc = stream.encoding if enc is None: enc = sys.getdefaultencoding() except AttributeError: return builtins.print(*objects, **kwargs) texts = [] for object in objects: try: if type(object) is bytes: if sys.version_info < (3, 0): # in python 2 bytes must be converted to str before decode object = str(object) original_text = object.decode(enc, errors='replace') else: if sys.version_info < (3, 0): object = unicode(object) original_text = object.encode(enc, errors='replace').decode(enc, errors='replace') except UnicodeEncodeError: original_text = unicode(object).encode(enc, errors='replace').decode(enc, errors='replace') texts.append(original_text) return builtins.print(*texts, **kwargs)
def wrp_adder(*args, **kwargs): if DEBUG_ADDERS or VERB_CONTROL: print('+------') print('[ADD]: ' + get_funcname(func)) funccall_str = ut.func_str(func, args, kwargs, packed=True) print('\n' + funccall_str + '\n') print('L------') if VERB_CONTROL: print('[ADD]: ' + get_funcname(func)) builtins.print('\n' + ut.func_str(func, args, kwargs) + '\n') return func_(*args, **kwargs)
def wrp_adder(*args, **kwargs): if DEBUG_ADDERS or VERB_CONTROL: print("+------") print("[ADD]: " + get_funcname(func)) funccall_str = ut.func_str(func, args, kwargs, packed=True) print("\n" + funccall_str + "\n") print("L------") if VERB_CONTROL: print("[ADD]: " + get_funcname(func)) builtins.print("\n" + ut.func_str(func, args, kwargs) + "\n") return func_(*args, **kwargs)
def rrr(verbose=True): """ Dynamic module reloading """ if not __RELOAD_OK__: raise Exception('Reloading has been forced off') try: import imp if verbose and not QUIET: builtins.print('RELOAD: ' + str(module_prefix) + ' __name__=' + module_name) imp.reload(module) except Exception as ex: print(ex) print('%s Failed to reload' % module_prefix) raise
def reload_module(module, verbose=True): if not __RELOAD_OK__: raise Exception('Reloading has been forced off') try: import imp if verbose and not QUIET: module_name = getattr(module, '__name__', '???') builtins.print('RELOAD: module __name__=' + module_name) imp.reload(module) except Exception as ex: print(ex) print('Failed to reload %r' % (module, )) raise
def reload_module(module, verbose=True): if not __RELOAD_OK__: raise Exception('Reloading has been forced off') try: import imp if verbose and not QUIET: module_name = getattr(module, '__name__', '???') builtins.print('RELOAD: module __name__=' + module_name) imp.reload(module) except Exception as ex: print(ex) print('Failed to reload %r' % (module,)) raise
def noinject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=0): """ Use in modules that do not have inject in them Does not inject anything into the module. Just lets utool know that a module is being imported so the import order can be debuged """ if PRINT_INJECT_ORDER: from utool._internal import meta_util_dbg callername = meta_util_dbg.get_caller_name(N=2 + N, strict=False) lineno = meta_util_dbg.get_caller_lineno(N=2 + N, strict=False) fmtdict = dict(N=N, lineno=lineno, callername=callername, modname=module_name) msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}'.format(**fmtdict) builtins.print(msg)
def noinject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=0, via=None): """ Use in modules that do not have inject in them Does not inject anything into the module. Just lets utool know that a module is being imported so the import order can be debuged """ if PRINT_INJECT_ORDER: from utool._internal import meta_util_dbg callername = meta_util_dbg.get_caller_name(N=N + 1, strict=False) lineno = meta_util_dbg.get_caller_lineno(N=N + 1, strict=False) suff = ' via %s' % (via,) if via else '' fmtdict = dict(N=N, lineno=lineno, callername=callername, modname=module_name, suff=suff) msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}{suff}'.format(**fmtdict) builtins.print(msg) if EXIT_ON_INJECT_MODNAME == module_name: builtins.print('...exiting') assert False, 'exit in inject requested'
def add_logging_handler(handler, format_='file'): """ mostly for util_logging internals """ global __UTOOL_ROOT_LOGGER__ if __UTOOL_ROOT_LOGGER__ is None: builtins.print('[WARNING] logger not started, cannot add handler') return # create formatter and add it to the handlers #logformat = '%Y-%m-%d %H:%M:%S' #logformat = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' timeformat = '%H:%M:%S' if format_ == 'file': logformat = '[%(asctime)s]%(message)s' elif format_ == 'stdout': logformat = '%(message)s' else: raise AssertionError('unknown logging format_: %r' % format_) # Create formatter for handlers formatter = logging.Formatter(logformat, timeformat) handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) __UTOOL_ROOT_LOGGER__.addHandler(handler)
PRINT_ALL_CALLERS = '--print-all-callers' in sys.argv USE_ASSERT = not NO_ASSERTS NOT_QUIET = not QUIET PRINT_INJECT_ORDER = VERYVERBOSE or '--print-inject-order' in sys.argv LOGGING_VERBOSE = VERYVERBOSE or '--verb-logging' in sys.argv if PRINT_INJECT_ORDER: # HACK from utool._internal import meta_util_dbg from six.moves import builtins N = 0 callername = meta_util_dbg.get_caller_name(N=2 + N, strict=False) lineno = meta_util_dbg.get_caller_lineno(N=2 + N, strict=False) fmtdict = dict(N=N, lineno=lineno, callername=callername, modname=__name__) msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}'.format(**fmtdict) builtins.print(msg) #def get_argval(arg, type_=None, default=None): # arg_after = default # if type_ is bool: # arg_after = False if default is None else default # try: # argx = sys.argv.index(arg) # if argx < len(sys.argv): # if type_ is bool: # arg_after = True # else: # try: # arg_after_ = sys.argv[argx + 1] # if type_ in [types.BooleanType] and isinstance(arg_after_, six.string_types): # if arg_after_.lower() == 'true':
def wrp_deleter(*args, **kwargs): if VERB_CONTROL: print("[DELETE]: " + get_funcname(func)) builtins.print("\n" + ut.func_str(func, args, kwargs) + "\n") return func_(*args, **kwargs)
def test(): print('enter test') log_fpath1 = utool.get_app_resource_dir('utool', 'test_logfile1.txt') log_fpath2 = utool.get_app_resource_dir('utool', 'test_logfile2.txt') utool.start_logging(log_fpath1, 'w') func1() func2() utool.stop_logging() print('\n\n') print('This line is NOT logged') print('\n\n') utool.start_logging(log_fpath2, 'w') print('This line is logged') utool.stop_logging() log1 = utool.read_from(log_fpath1, verbose=False) log2 = utool.read_from(log_fpath2, verbose=False) target1 = utool.unindent(''' <__LOG_START__> logging to log_fpath=%r [test][func1]enter func1 [test][func1]exit func1 [test][func2]enter func2 [test][func2][func1]enter func1 [test][func2][func1]exit func1 [test][func2]exit func2 <__LOG_STOP__>''' % log_fpath1).strip() target2 = utool.unindent(''' <__LOG_START__> logging to log_fpath=%r [test]This line is logged <__LOG_STOP__>''' % log_fpath2).strip() output1 = remove_timestamp(log1).strip() output2 = remove_timestamp(log2).strip() try: assert target1 == output1, 'target1 failed' assert target2 == output2, 'target2 failed' builtins.print('TEST PASSED') except AssertionError: builtins.print('\n<!!! TEST FAILED !!!>') builtins.print('\ntarget1:') builtins.print(target1) builtins.print('\noutput1:') builtins.print(output1) builtins.print('\ntarget2:') builtins.print(target2) builtins.print('\noutput2:') builtins.print(output2) builtins.print('</!!! TEST FAILED !!!>\n') raise
def wrp_deleter(*args, **kwargs): if VERB_CONTROL: print('[DELETE]: ' + get_funcname(func)) builtins.print('\n' + ut.func_str(func, args, kwargs) + '\n') return func_(*args, **kwargs)
or '--verb-import' in sys.argv or '--verb-import' in sys.argv or '--verbose-import' in sys.argv) LOGGING_VERBOSE = VERYVERBOSE or '--verb-logging' in sys.argv if PRINT_INJECT_ORDER: # HACK from utool._internal import meta_util_dbg from six.moves import builtins N = 0 callername = meta_util_dbg.get_caller_name(N=2 + N, strict=False) lineno = meta_util_dbg.get_caller_lineno(N=2 + N, strict=False) fmtdict = dict(N=N, lineno=lineno, callername=callername, modname=__name__) msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}'.format( **fmtdict) builtins.print(msg) def _try_cast(val, type_): if type_ in [types.BooleanType] and isinstance(val, six.string_types): if val.lower() == 'true': newval = True elif val.lower() == 'false': newval = True else: newval = type_(val) return newval def get_argflag(flag): return flag in sys.argv