def main_xonsh(args): """Main entry point for xonsh cli.""" if not ON_WINDOWS: def func_sig_ttin_ttou(n, f): pass signal.signal(signal.SIGTTIN, func_sig_ttin_ttou) signal.signal(signal.SIGTTOU, func_sig_ttin_ttou) events.on_post_init.fire() env = builtins.__xonsh__.env shell = builtins.__xonsh__.shell history = builtins.__xonsh__.history exit_code = 0 try: if args.mode == XonshMode.interactive: # enter the shell env["XONSH_INTERACTIVE"] = True ignore_sigtstp() if env["XONSH_INTERACTIVE"] and not any( os.path.isfile(i) for i in env["XONSHRC"] ): print_welcome_screen() events.on_pre_cmdloop.fire() try: shell.shell.cmdloop() finally: events.on_post_cmdloop.fire() elif args.mode == XonshMode.single_command: # run a single command and exit run_code_with_cache(args.command.lstrip(), shell.execer, mode="single") if history is not None and history.last_cmd_rtn is not None: exit_code = history.last_cmd_rtn elif args.mode == XonshMode.script_from_file: # run a script contained in a file path = os.path.abspath(os.path.expanduser(args.file)) if os.path.isfile(path): sys.argv = [args.file] + args.args env.update(make_args_env()) # $ARGS is not sys.argv env["XONSH_SOURCE"] = path shell.ctx.update({"__file__": args.file, "__name__": "__main__"}) run_script_with_cache( args.file, shell.execer, glb=shell.ctx, loc=None, mode="exec" ) else: print("xonsh: {0}: No such file or directory.".format(args.file)) exit_code = 1 elif args.mode == XonshMode.script_from_stdin: # run a script given on stdin code = sys.stdin.read() run_code_with_cache( code, shell.execer, glb=shell.ctx, loc=None, mode="exec" ) finally: events.on_exit.fire() postmain(args) return exit_code
def test_make_args_env(): obs = make_args_env(["script", "1", "2", "3"]) exp = { "ARGS": ["script", "1", "2", "3"], "ARG0": "script", "ARG1": "1", "ARG2": "2", "ARG3": "3", } assert exp == obs
def test_make_args_env(): obs = make_args_env(['script', '1', '2', '3']) exp = { 'ARGS': ['script', '1', '2', '3'], 'ARG0': 'script', 'ARG1': '1', 'ARG2': '2', 'ARG3': '3', } assert exp == obs
def main_xonsh(args): """Main entry point for xonsh cli.""" if not ON_WINDOWS: def func_sig_ttin_ttou(n, f): pass signal.signal(signal.SIGTTIN, func_sig_ttin_ttou) signal.signal(signal.SIGTTOU, func_sig_ttin_ttou) events.on_post_init.fire() env = builtins.__xonsh__.env shell = builtins.__xonsh__.shell try: if args.mode == XonshMode.interactive: # enter the shell env["XONSH_INTERACTIVE"] = True ignore_sigtstp() if env["XONSH_INTERACTIVE"] and not any( os.path.isfile(i) for i in env["XONSHRC"] ): print_welcome_screen() events.on_pre_cmdloop.fire() try: shell.shell.cmdloop() finally: events.on_post_cmdloop.fire() elif args.mode == XonshMode.single_command: # run a single command and exit run_code_with_cache(args.command.lstrip(), shell.execer, mode="single") elif args.mode == XonshMode.script_from_file: # run a script contained in a file path = os.path.abspath(os.path.expanduser(args.file)) if os.path.isfile(path): sys.argv = [args.file] + args.args env.update(make_args_env()) # $ARGS is not sys.argv env["XONSH_SOURCE"] = path shell.ctx.update({"__file__": args.file, "__name__": "__main__"}) run_script_with_cache( args.file, shell.execer, glb=shell.ctx, loc=None, mode="exec" ) else: print("xonsh: {0}: No such file or directory.".format(args.file)) elif args.mode == XonshMode.script_from_stdin: # run a script given on stdin code = sys.stdin.read() run_code_with_cache( code, shell.execer, glb=shell.ctx, loc=None, mode="exec" ) finally: events.on_exit.fire() postmain(args)
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 main_xonsh(args): """Main entry point for xonsh cli.""" if not ON_WINDOWS: def func_sig_ttin_ttou(n, f): pass signal.signal(signal.SIGTTIN, func_sig_ttin_ttou) signal.signal(signal.SIGTTOU, func_sig_ttin_ttou) events.on_post_init.fire() env = builtins.__xonsh_env__ shell = builtins.__xonsh_shell__ try: if args.mode == XonshMode.interactive: # enter the shell env['XONSH_INTERACTIVE'] = True ignore_sigtstp() if (env['XONSH_INTERACTIVE'] and not any(os.path.isfile(i) for i in env['XONSHRC'])): print_welcome_screen() events.on_pre_cmdloop.fire() try: shell.shell.cmdloop() finally: events.on_post_cmdloop.fire() elif args.mode == XonshMode.single_command: # run a single command and exit run_code_with_cache(args.command.lstrip(), shell.execer, mode='single') elif args.mode == XonshMode.script_from_file: # run a script contained in a file path = os.path.abspath(os.path.expanduser(args.file)) if os.path.isfile(path): sys.argv = [args.file] + args.args env.update(make_args_env()) # $ARGS is not sys.argv env['XONSH_SOURCE'] = path shell.ctx.update({'__file__': args.file, '__name__': '__main__'}) run_script_with_cache(args.file, shell.execer, glb=shell.ctx, loc=None, mode='exec') else: print('xonsh: {0}: No such file or directory.'.format(args.file)) elif args.mode == XonshMode.script_from_stdin: # run a script given on stdin code = sys.stdin.read() run_code_with_cache(code, shell.execer, glb=shell.ctx, loc=None, mode='exec') finally: events.on_exit.fire() postmain(args)
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 main_xonsh(args): """Main entry point for xonsh cli.""" if not ON_WINDOWS: def func_sig_ttin_ttou(n, f): pass signal.signal(signal.SIGTTIN, func_sig_ttin_ttou) signal.signal(signal.SIGTTOU, func_sig_ttin_ttou) events.on_post_init.fire() env = XSH.env shell = XSH.shell history = XSH.history exit_code = 0 if shell and not env["XONSH_INTERACTIVE"]: shell.ctx.update({"exit": sys.exit}) # store a sys.exc_info() tuple to record any exception that might occur in the user code that we are about to execute # if this does not change, no exceptions were thrown. Otherwise, print a traceback that does not expose xonsh internals exc_info = None, None, None try: if args.mode == XonshMode.interactive: # enter the shell # Setted again here because it is possible to call main_xonsh() without calling premain(), namely in the tests. env["XONSH_INTERACTIVE"] = True ignore_sigtstp() if (env["XONSH_INTERACTIVE"] and not any(os.path.isfile(i) for i in env["XONSHRC"]) and not any(os.path.isdir(i) for i in env["XONSHRC_DIR"])): print_welcome_screen() events.on_pre_cmdloop.fire() try: shell.shell.cmdloop() finally: events.on_post_cmdloop.fire() elif args.mode == XonshMode.single_command: # run a single command and exit exc_info = run_code_with_cache( args.command.lstrip(), "<string>", shell.execer, glb=shell.ctx, mode="single", ) if history is not None and history.last_cmd_rtn is not None: exit_code = history.last_cmd_rtn elif args.mode == XonshMode.script_from_file: # run a script contained in a file path = os.path.abspath(os.path.expanduser(args.file)) if os.path.isfile(path): sys.argv = [args.file] + args.args env.update(make_args_env()) # $ARGS is not sys.argv env["XONSH_SOURCE"] = path shell.ctx.update({ "__file__": args.file, "__name__": "__main__" }) exc_info = run_script_with_cache(args.file, shell.execer, glb=shell.ctx, loc=None, mode="exec") else: print(f"xonsh: {args.file}: No such file or directory.") exit_code = 1 elif args.mode == XonshMode.script_from_stdin: # run a script given on stdin code = sys.stdin.read() exc_info = run_code_with_cache(code, "<stdin>", shell.execer, glb=shell.ctx, loc=None, mode="exec") except SyntaxError: exit_code = 1 debug_level = env.get("XONSH_DEBUG", 0) if debug_level == 0: # print error without tracktrace display_error_message(sys.exc_info()) else: # pass error to finally clause exc_info = sys.exc_info() finally: if exc_info != (None, None, None): err_type, err, _ = exc_info if err_type is SystemExit: raise err else: traceback.print_exception(*exc_info) exit_code = 1 events.on_exit.fire() postmain(args) return exit_code