def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead. """ env = builtins.__xonsh_env__ encoding = env.get('XONSH_ENCODING') errors = env.get('XONSH_ENCODING_ERRORS') for i, fname in enumerate(args): fpath = fname if not os.path.isfile(fpath): fpath = locate_binary(fname) if fpath is None: if env.get('XONSH_DEBUG'): print('source: {}: No such file'.format(fname), file=sys.stderr) if i == 0: raise RuntimeError('must source at least one file, ' + fname + 'does not exist.') break with open(fpath, 'r', encoding=encoding, errors=errors) as fp: src = fp.read() if not src.endswith('\n'): src += '\n' ctx = builtins.__xonsh_ctx__ updates = {'__file__': fpath, '__name__': os.path.abspath(fpath)} with env.swap(ARGS=args[i+1:]), swap_values(ctx, updates): builtins.execx(src, 'exec', ctx, filename=fpath)
def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead. """ env = builtins.__xonsh_env__ encoding = env.get('XONSH_ENCODING') errors = env.get('XONSH_ENCODING_ERRORS') for i, fname in enumerate(args): fpath = fname if not os.path.isfile(fpath): fpath = locate_binary(fname) if fpath is None: if env.get('XONSH_DEBUG'): print('source: {}: No such file'.format(fname), file=sys.stderr) if i == 0: raise RuntimeError('must source at least one file, ' + fname + 'does not exist.') break with open(fpath, 'r', encoding=encoding, errors=errors) as fp: src = fp.read() if not src.endswith('\n'): src += '\n' ctx = builtins.__xonsh_ctx__ updates = {'__file__': fpath, '__name__': os.path.abspath(fpath)} with env.swap(ARGS=args[i + 1:]), swap_values(ctx, updates): builtins.execx(src, 'exec', ctx, filename=fpath)
def bang_n(args, stdin=None): """Re-runs the nth command as specified in the argument.""" global _BANG_N_PARSER if _BANG_N_PARSER is None: parser = _BANG_N_PARSER = ArgumentParser( '!n', usage='!n <n>', description="Re-runs the nth command as specified in the argument." ) parser.add_argument('n', type=int, help='the command to rerun, may be negative') else: parser = _BANG_N_PARSER ns = parser.parse_args(args) hist = builtins.__xonsh_history__ nhist = len(hist) n = nhist + ns.n if ns.n < 0 else ns.n if n < 0 or n >= nhist: raise IndexError('n out of range, {0} for history len {1}'.format( ns.n, nhist)) cmd = hist.inps[n] if cmd.startswith('!'): raise XonshError('xonsh: error: recursive call to !n') builtins.execx(cmd)
def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead""" for fname in args: if not os.path.isfile(fname): fname = locate_binary(fname) with open(fname, 'r') as fp: builtins.execx(fp.read(), 'exec', builtins.__xonsh_ctx__)
def timeit_alias(args, stdin=None): """Runs timing study on arguments.""" # some real args number = 0 quiet = False repeat = 3 precision = 3 # setup ctx = builtins.__xonsh__.ctx timer = Timer(timer=clock) stmt = " ".join(args) innerstr = INNER_TEMPLATE.format(stmt=stmt) # Track compilation time so it can be reported if too long # Minimum time above which compilation time will be reported tc_min = 0.1 t0 = clock() innercode = builtins.compilex(innerstr, filename="<xonsh-timeit>", mode="exec", glbs=ctx) tc = clock() - t0 # get inner func ns = {} builtins.execx(innercode, glbs=ctx, locs=ns, mode="exec") timer.inner = ns["inner"] # Check if there is a huge difference between the best and worst timings. worst_tuning = 0 if number == 0: # determine number so that 0.2 <= total time < 2.0 number = 1 for _ in range(1, 10): time_number = timer.timeit(number) worst_tuning = max(worst_tuning, time_number / number) if time_number >= 0.2: break number *= 10 all_runs = timer.repeat(repeat, number) best = min(all_runs) / number # print some debug info if not quiet: worst = max(all_runs) / number if worst_tuning: worst = max(worst, worst_tuning) # Check best timing is greater than zero to avoid a # ZeroDivisionError. # In cases where the slowest timing is less than 10 microseconds # we assume that it does not really matter if the fastest # timing is 4 times faster than the slowest timing or not. if worst > 4 * best and best > 0 and worst > 1e-5: print(("The slowest run took {0:0.2f} times longer than the " "fastest. This could mean that an intermediate result " "is being cached.").format(worst / best)) print("{0} loops, best of {1}: {2} per loop".format( number, repeat, format_time(best, precision))) if tc > tc_min: print("Compiler time: {0:.2f} s".format(tc)) return
def timeit_alias(args, stdin=None): """Runs timing study on arguments.""" # some real args number = 0 quiet = False repeat = 3 precision = 3 # setup ctx = builtins.__xonsh_ctx__ timer = Timer(timer=clock) stmt = " ".join(args) innerstr = INNER_TEMPLATE.format(stmt=stmt) # Track compilation time so it can be reported if too long # Minimum time above which compilation time will be reported tc_min = 0.1 t0 = clock() innercode = builtins.compilex(innerstr, filename="<xonsh-timeit>", mode="exec", glbs=ctx) tc = clock() - t0 # get inner func ns = {} builtins.execx(innercode, glbs=ctx, locs=ns, mode="exec") timer.inner = ns["inner"] # Check if there is a huge difference between the best and worst timings. worst_tuning = 0 if number == 0: # determine number so that 0.2 <= total time < 2.0 number = 1 for _ in range(1, 10): time_number = timer.timeit(number) worst_tuning = max(worst_tuning, time_number / number) if time_number >= 0.2: break number *= 10 all_runs = timer.repeat(repeat, number) best = min(all_runs) / number # print some debug info if not quiet: worst = max(all_runs) / number if worst_tuning: worst = max(worst, worst_tuning) # Check best timing is greater than zero to avoid a # ZeroDivisionError. # In cases where the slowest timing is lesser than 10 micoseconds # we assume that it does not really matter if the fastest # timing is 4 times faster than the slowest timing or not. if worst > 4 * best and best > 0 and worst > 1e-5: print( ( "The slowest run took {0:0.2f} times longer than the " "fastest. This could mean that an intermediate result " "is being cached." ).format(worst / best) ) print("{0} loops, best of {1}: {2} per loop".format(number, repeat, format_time(best, precision))) if tc > tc_min: print("Compiler time: {0:.2f} s".format(tc)) return
def bang_n(args, stdin=None): """Re-runs the nth command as specified in the argument.""" ns = _BANG_N_PARSER.parse_args(args) hist = builtins.__xonsh_history__ nhist = len(hist) n = nhist + ns.n if ns.n < 0 else ns.n if n < 0 or n >= nhist: raise IndexError('n out of range, {0} for history len {1}'.format(ns.n, nhist)) cmd = hist.inps[n] if cmd.startswith('!'): raise XonshError('xonsh: error: recursive call to !n') builtins.execx(cmd)
def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead. """ env = builtins.__xonsh_env__ encoding = env.get('XONSH_ENCODING') errors = env.get('XONSH_ENCODING_ERRORS') for fname in args: if not os.path.isfile(fname): fname = locate_binary(fname) with open(fname, 'r', encoding=encoding, errors=errors) as fp: builtins.execx(fp.read(), 'exec', builtins.__xonsh_ctx__)
def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead. """ env = builtins.__xonsh_env__ encoding = env.get("XONSH_ENCODING") errors = env.get("XONSH_ENCODING_ERRORS") for fname in args: if not os.path.isfile(fname): fname = locate_binary(fname) with open(fname, "r", encoding=encoding, errors=errors) as fp: src = fp.read() if not src.endswith("\n"): src += "\n" builtins.execx(src, "exec", builtins.__xonsh_ctx__)
def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead. """ env = builtins.__xonsh_env__ encoding = env.get("XONSH_ENCODING") errors = env.get("XONSH_ENCODING_ERRORS") for i, fname in enumerate(args): fpath = fname if not os.path.isfile(fpath): fpath = locate_binary(fname) if fpath is None: if env.get("XONSH_DEBUG"): print("source: {}: No such file".format(fname), file=sys.stderr) if i == 0: raise RuntimeError("must source at least one file, " + fname + "does not exist.") break _, fext = os.path.splitext(fpath) if fext and fext != ".xsh" and fext != ".py": raise RuntimeError( "attempting to source non-xonsh file! If you are " "trying to source a file in another language, " "then please use the appropriate source command. " "For example, source-bash script.sh") with open(fpath, "r", encoding=encoding, errors=errors) as fp: src = fp.read() if not src.endswith("\n"): src += "\n" ctx = builtins.__xonsh_ctx__ updates = {"__file__": fpath, "__name__": os.path.abspath(fpath)} with env.swap(**make_args_env(args[i + 1:])), swap_values( ctx, updates): try: builtins.execx(src, "exec", ctx, filename=fpath) except Exception: print_color( "{RED}You may be attempting to source non-xonsh file! " "{NO_COLOR}If you are trying to source a file in " "another language, then please use the appropriate " "source command. For example, {GREEN}source-bash " "script.sh{NO_COLOR}", file=sys.stderr, ) raise
def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead. """ env = builtins.__xonsh__.env encoding = env.get("XONSH_ENCODING") errors = env.get("XONSH_ENCODING_ERRORS") for i, fname in enumerate(args): fpath = fname if not os.path.isfile(fpath): fpath = locate_binary(fname) if fpath is None: if env.get("XONSH_DEBUG"): print("source: {}: No such file".format(fname), file=sys.stderr) if i == 0: raise RuntimeError( "must source at least one file, " + fname + "does not exist." ) break _, fext = os.path.splitext(fpath) if fext and fext != ".xsh" and fext != ".py": raise RuntimeError( "attempting to source non-xonsh file! If you are " "trying to source a file in another language, " "then please use the appropriate source command. " "For example, source-bash script.sh" ) with open(fpath, "r", encoding=encoding, errors=errors) as fp: src = fp.read() if not src.endswith("\n"): src += "\n" ctx = builtins.__xonsh__.ctx updates = {"__file__": fpath, "__name__": os.path.abspath(fpath)} with env.swap(**make_args_env(args[i + 1 :])), swap_values(ctx, updates): try: builtins.execx(src, "exec", ctx, filename=fpath) except Exception: print_color( "{RED}You may be attempting to source non-xonsh file! " "{NO_COLOR}If you are trying to source a file in " "another language, then please use the appropriate " "source command. For example, {GREEN}source-bash " "script.sh{NO_COLOR}", file=sys.stderr, ) raise
def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead. """ env = builtins.__xonsh_env__ encoding = env.get('XONSH_ENCODING') errors = env.get('XONSH_ENCODING_ERRORS') for i, fname in enumerate(args): fpath = fname if not os.path.isfile(fpath): fpath = locate_binary(fname) if fpath is None: if env.get('XONSH_DEBUG'): print('source: {}: No such file'.format(fname), file=sys.stderr) if i == 0: raise RuntimeError('must source at least one file, ' + fname + 'does not exist.') break _, fext = os.path.splitext(fpath) if fext and fext != '.xsh' and fext != '.py': raise RuntimeError( 'attempting to source non-xonsh file! If you are ' 'trying to source a file in another language, ' 'then please use the appropriate source command. ' 'For example, source-bash script.sh') with open(fpath, 'r', encoding=encoding, errors=errors) as fp: src = fp.read() if not src.endswith('\n'): src += '\n' ctx = builtins.__xonsh_ctx__ updates = {'__file__': fpath, '__name__': os.path.abspath(fpath)} with env.swap(**make_args_env(args[i + 1:])), swap_values( ctx, updates): try: builtins.execx(src, 'exec', ctx, filename=fpath) except Exception: print_color( '{RED}You may be attempting to source non-xonsh file! ' '{NO_COLOR}If you are trying to source a file in ' 'another language, then please use the appropriate ' 'source command. For example, {GREEN}source-bash ' 'script.sh{NO_COLOR}', file=sys.stderr) raise
def bang_n(args, stdin=None): """Re-runs the nth command as specified in the argument.""" global _BANG_N_PARSER if _BANG_N_PARSER is None: parser = _BANG_N_PARSER = ArgumentParser('!n', usage='!n <n>', description="Re-runs the nth command as specified in the argument.") parser.add_argument('n', type=int, help='the command to rerun, may be negative') else: parser = _BANG_N_PARSER ns = parser.parse_args(args) hist = builtins.__xonsh_history__ nhist = len(hist) n = nhist + ns.n if ns.n < 0 else ns.n if n < 0 or n >= nhist: raise IndexError('n out of range, {0} for history len {1}'.format(ns.n, nhist)) cmd = hist.inps[n] if cmd.startswith('!'): raise XonshError('xonsh: error: recursive call to !n') builtins.execx(cmd)
def bang_n(args, stdin=None): """ Re-runs the nth command as specified in the argument. """ if len(args) == 1: try: # 1 is subtracted here to exclude the current command index = -int(args[0])-1 except: return 'xonsh: !n: usage: !n n\n' if len(builtins.ordered_history) >= abs(index): cmd = builtins.ordered_history[index]['cmd'] if '!!' not in cmd and '!n' not in cmd: builtins.execx(builtins.ordered_history[index]['cmd']) else: return 'xonsh: error: recursive call to !! or !n\n' else: return 'xonsh: no previous command\n' else: return 'xonsh: !n: usage: !n n\n'
def source_alias(args, stdin=None): """Executes the contents of the provided files in the current context. If sourced file isn't found in cwd, search for file along $PATH to source instead. """ env = builtins.__xonsh_env__ encoding = env.get('XONSH_ENCODING') errors = env.get('XONSH_ENCODING_ERRORS') for i, fname in enumerate(args): fpath = fname if not os.path.isfile(fpath): fpath = locate_binary(fname) if fpath is None: if env.get('XONSH_DEBUG'): print('source: {}: No such file'.format(fname), file=sys.stderr) if i == 0: raise RuntimeError('must source at least one file, ' + fname + 'does not exist.') break _, fext = os.path.splitext(fpath) if fext and fext != '.xsh' and fext != '.py': raise RuntimeError('attempting to source non-xonsh file! If you are ' 'trying to source a file in another language, ' 'then please use the appropriate source command. ' 'For example, source-bash script.sh') with open(fpath, 'r', encoding=encoding, errors=errors) as fp: src = fp.read() if not src.endswith('\n'): src += '\n' ctx = builtins.__xonsh_ctx__ updates = {'__file__': fpath, '__name__': os.path.abspath(fpath)} with env.swap(ARGS=args[i+1:]), swap_values(ctx, updates): try: builtins.execx(src, 'exec', ctx, filename=fpath) except Exception: print_color('{RED}You may be attempting to source non-xonsh file! ' '{NO_COLOR}If you are trying to source a file in ' 'another language, then please use the appropriate ' 'source command. For example, {GREEN}source-bash ' 'script.sh{NO_COLOR}', file=sys.stderr) raise