def __init__(self, completekey='tab', stdin=None, stdout=None, ctx=None): super(Shell, self).__init__(completekey=completekey, stdin=stdin, stdout=stdout) self.execer = Execer() env = builtins.__xonsh_env__ self.ctx = ctx if ctx is not None else \ xonshrc_context(rcfile=env.get('XONSHRC', None), execer=self.execer) self.completer = Completer() self.buffer = [] self.need_more_lines = False self.mlprompt = None setup_readline()
def xonsh_execer(monkeypatch): """Initiate the Execer with a mocked nop `load_builtins`""" monkeypatch.setattr('xonsh.built_ins.load_builtins.__code__', (lambda *args, **kwargs: None).__code__) execer = Execer(unload=False) builtins.__xonsh_execer__ = execer return execer
def xonsh_execer(monkeypatch): """Initiate the Execer with a mocked nop `load_builtins`""" execer = Execer() XSH.load(execer=execer) # TODO this monkeypatch *shouldn't* be useful now. monkeypatch.setattr(XSH, "execer", execer) yield execer
def start_services(shell_kwargs, args): """Starts up the essential services in the proper order. This returns the environment instance as a convenience. """ install_import_hooks() # create execer, which loads builtins ctx = shell_kwargs.get('ctx', {}) debug = to_bool_or_int(os.getenv('XONSH_DEBUG', '0')) events.on_timingprobe.fire(name='pre_execer_init') execer = Execer(xonsh_ctx=ctx, debug_level=debug, scriptcache=shell_kwargs.get('scriptcache', True), cacheall=shell_kwargs.get('cacheall', False)) events.on_timingprobe.fire(name='post_execer_init') # load rc files login = shell_kwargs.get('login', True) env = builtins.__xonsh_env__ rc = shell_kwargs.get('rc', None) rc = env.get('XONSHRC') if rc is None else rc if args.mode != XonshMode.interactive and not args.force_interactive: # Don't load xonshrc if not interactive shell rc = None events.on_pre_rc.fire() xonshrc_context(rcfiles=rc, execer=execer, ctx=ctx, env=env, login=login) events.on_post_rc.fire() # create shell builtins.__xonsh_shell__ = Shell(execer=execer, **shell_kwargs) ctx['__name__'] = '__main__' return env
def ctx(): """Create a global Shell instance to use in all the test.""" ctx = {'PATH': []} execer = Execer(xonsh_ctx=ctx) builtins.__xonsh_shell__ = Shell(execer=execer, ctx=ctx) yield del builtins.__xonsh_shell__
def _init_environ(self, ctx, config, rc, scriptcache, cacheall): self.ctx = {} if ctx is None else ctx debug = to_bool_or_int(os.getenv('XONSH_DEBUG', '0')) self.execer = Execer(config=config, login=self.login, xonsh_ctx=self.ctx, debug_level=debug) self.execer.scriptcache = scriptcache self.execer.cacheall = cacheall if self.stype != 'none' or self.login: # load xontribs from config file names = builtins.__xonsh_config__.get('xontribs', ()) for name in names: update_context(name, ctx=self.ctx) if getattr(update_context, 'bad_imports', None): prompt_xontrib_install(update_context.bad_imports) del update_context.bad_imports # load run control files env = builtins.__xonsh_env__ rc = env.get('XONSHRC') if rc is None else rc self.ctx.update( xonshrc_context(rcfiles=rc, execer=self.execer, initial=self.ctx)) self.ctx['__name__'] = '__main__'
def ctx(): """Create a global Shell instance to use in all the test.""" ctx = {"PATH": []} execer = Execer(xonsh_ctx=ctx) builtins.__xonsh__.shell = Shell(execer=execer, ctx=ctx, shell_type="none") yield builtins.__xonsh__.shell = None
def xonsh_execer(monkeypatch): """Initiate the Execer with a mocked nop `load_builtins`""" monkeypatch.setattr(xonsh.built_ins, 'load_builtins', lambda *args, **kwargs: None) execer = Execer(login=False, unload=False) builtins.__xonsh_execer__ = execer return execer
def setup(ctx=None, shell_type='none', env=(('RAISE_SUBPROC_ERROR', True), )): """Starts up a new xonsh shell. Calling this in function in another packages __init__.py will allow xonsh to be fully used in the package in headless or headed mode. This function is primarily indended to make starting up xonsh for 3rd party packages easier. Parameters ---------- ctx : dict-like or None, optional The xonsh context to start with. If None, an empty dictionary is provided. shell_type : str, optional The type of shell to start. By default this is 'none', indicating we should start in headless mode. env : dict-like, optional Environment to update the current environment with after the shell has been initialized. """ ctx = {} if ctx is None else ctx # setup xonsh ctx and execer builtins.__xonsh_ctx__ = ctx builtins.__xonsh_execer__ = Execer(xonsh_ctx=ctx) builtins.__xonsh_shell__ = Shell(builtins.__xonsh_execer__, ctx=ctx, shell_type='none') builtins.__xonsh_env__.update(env) install_import_hooks()
def install_import_hooks(execer=ARG_NOT_PRESENT): """ Install Xonsh import hooks in ``sys.meta_path`` in order for ``.xsh`` files to be importable and import events to be fired. Can safely be called many times, will be no-op if xonsh import hooks are already present. """ if execer is ARG_NOT_PRESENT: print_warning("No execer was passed to install_import_hooks. " "This will become an error in future.") execer = XSH.execer if execer is None: execer = Execer() XSH.load(execer=execer) found_imp = found_event = False for hook in sys.meta_path: if isinstance(hook, XonshImportHook): found_imp = True elif isinstance(hook, XonshImportEventHook): found_event = True if not found_imp: sys.meta_path.append(XonshImportHook(execer)) if not found_event: sys.meta_path.insert(0, XonshImportEventHook())
def start_services(shell_kwargs, args): """Starts up the essential services in the proper order. This returns the environment instance as a convenience. """ install_import_hooks() # create execer, which loads builtins ctx = shell_kwargs.get("ctx", {}) debug = to_bool_or_int(os.getenv("XONSH_DEBUG", "0")) events.on_timingprobe.fire(name="pre_execer_init") execer = Execer( xonsh_ctx=ctx, debug_level=debug, scriptcache=shell_kwargs.get("scriptcache", True), cacheall=shell_kwargs.get("cacheall", False), ) events.on_timingprobe.fire(name="post_execer_init") # load rc files login = shell_kwargs.get("login", True) env = builtins.__xonsh__.env rc = shell_kwargs.get("rc", None) rc = env.get("XONSHRC") if rc is None else rc if args.mode != XonshMode.interactive and not args.force_interactive: # Don't load xonshrc if not interactive shell rc = None events.on_pre_rc.fire() xonshrc_context(rcfiles=rc, execer=execer, ctx=ctx, env=env, login=login) events.on_post_rc.fire() # create shell builtins.__xonsh__.shell = Shell(execer=execer, **shell_kwargs) ctx["__name__"] = "__main__" return env
def start_services(shell_kwargs, args, pre_env=None): """Starts up the essential services in the proper order. This returns the environment instance as a convenience. """ if pre_env is None: pre_env = {} # create execer, which loads builtins ctx = shell_kwargs.get("ctx", {}) debug = to_bool_or_int(os.getenv("XONSH_DEBUG", "0")) events.on_timingprobe.fire(name="pre_execer_init") execer = Execer( filename="<stdin>", debug_level=debug, scriptcache=shell_kwargs.get("scriptcache", True), cacheall=shell_kwargs.get("cacheall", False), ) XSH.load(ctx=ctx, execer=execer) events.on_timingprobe.fire(name="post_execer_init") install_import_hooks(execer) env = XSH.env for k, v in pre_env.items(): env[k] = v _autoload_xontribs(env) _load_rc_files(shell_kwargs, args, env, execer, ctx) # create shell XSH.shell = Shell(execer=execer, **shell_kwargs) ctx["__name__"] = "__main__" return env
def start_services(shell_kwargs, args, pre_env=None): """Starts up the essential services in the proper order. This returns the environment instance as a convenience. """ if pre_env is None: pre_env = {} # create execer, which loads builtins ctx = shell_kwargs.get("ctx", {}) debug = to_bool_or_int(os.getenv("XONSH_DEBUG", "0")) events.on_timingprobe.fire(name="pre_execer_init") execer = Execer( debug_level=debug, scriptcache=shell_kwargs.get("scriptcache", True), cacheall=shell_kwargs.get("cacheall", False), ) XSH.load(ctx=ctx, execer=execer) events.on_timingprobe.fire(name="post_execer_init") install_import_hooks(execer) # load rc files login = shell_kwargs.get("login", True) rc_cli = shell_kwargs.get("rc") env = XSH.env for k, v in pre_env.items(): env[k] = v # determine which RC files to load, including whether any RC directories # should be scanned for such files if shell_kwargs.get("norc") or (args.mode != XonshMode.interactive and not args.force_interactive and not args.login): # if --no-rc was passed, or we're not in an interactive shell and # interactive mode was not forced, then disable loading RC files and dirs rc = () rcd = () elif rc_cli: # if an explicit --rc was passed, then we should load only that RC # file, and nothing else (ignore both XONSHRC and XONSHRC_DIR) rc = [r for r in rc_cli if os.path.isfile(r)] rcd = [r for r in rc_cli if os.path.isdir(r)] else: # otherwise, get the RC files from XONSHRC, and RC dirs from XONSHRC_DIR rc = env.get("XONSHRC") rcd = env.get("XONSHRC_DIR") events.on_pre_rc.fire() XSH.rc_files = xonshrc_context(rcfiles=rc, rcdirs=rcd, execer=execer, ctx=ctx, env=env, login=login) events.on_post_rc.fire() # create shell XSH.shell = Shell(execer=execer, **shell_kwargs) ctx["__name__"] = "__main__" return env
def _init_environ(self, ctx, config, rc): self.execer = Execer(config=config) env = builtins.__xonsh_env__ if ctx is None: rc = env.get('XONSHRC') if rc is None else rc self.ctx = xonshrc_context(rcfiles=rc, execer=self.execer) else: self.ctx = ctx builtins.__xonsh_ctx__ = self.ctx self.ctx['__name__'] = '__main__'
def session_vars(): """keep costly vars per session""" from xonsh.environ import Env, default_env from xonsh.commands_cache import CommandsCache return { "execer": Execer(unload=False), "env": Env(default_env()), "commands_cache": CommandsCache(), }
def _init_environ(self, ctx): self.execer = Execer() env = builtins.__xonsh_env__ if ctx is not None: self.ctx = ctx else: rc = env.get('XONSHRC') self.ctx = xonshrc_context(rcfiles=rc, execer=self.execer) builtins.__xonsh_ctx__ = self.ctx self.ctx['__name__'] = '__main__'
def execer(self): if hasattr(builtins, '__xonsh_execer__'): execer = builtins.__xonsh_execer__ if self._execer is not None: self._execer = None elif self._execer is None: self._execer = execer = Execer(unload=False) else: execer = self._execer return execer
def execer(self): if XSH.execer is not None: execer = XSH.execer if self._execer is not None: self._execer = None elif self._execer is None: self._execer = execer = Execer(unload=False) else: execer = self._execer return execer
def xonsh_execer(monkeypatch): """Initiate the Execer with a mocked nop `load_builtins`""" monkeypatch.setattr( "xonsh.built_ins.load_builtins.__code__", (lambda *args, **kwargs: None).__code__, ) if not hasattr(builtins, "__xonsh__"): ensure_attached_session(XonshSession()) execer = Execer(unload=False) builtins.__xonsh__.execer = execer return execer
def execer(self): if (hasattr(builtins, "__xonsh__") and hasattr(builtins.__xonsh__, "execer") and builtins.__xonsh__.execer is not None): execer = builtins.__xonsh__.execer if self._execer is not None: self._execer = None elif self._execer is None: self._execer = execer = Execer(unload=False) else: execer = self._execer return execer
def session_vars(): """keep costly vars per session""" from xonsh.environ import Env, default_env from xonsh.commands_cache import CommandsCache execer = Execer() XSH.load(execer=execer) return { "execer": execer, "env": Env(default_env()), "commands_cache": CommandsCache(), }
def setup( ctx=None, shell_type="none", env=(("RAISE_SUBPROC_ERROR", True), ), aliases=(), xontribs=(), threadable_predictors=(), ): """Starts up a new xonsh shell. Calling this in function in another packages ``__init__.py`` will allow xonsh to be fully used in the package in headless or headed mode. This function is primarily indended to make starting up xonsh for 3rd party packages easier. Here is example of using this at the top of an ``__init__.py``:: from xonsh.main import setup setup() del setup Parameters ---------- ctx : dict-like or None, optional The xonsh context to start with. If None, an empty dictionary is provided. shell_type : str, optional The type of shell to start. By default this is 'none', indicating we should start in headless mode. env : dict-like, optional Environment to update the current environment with after the shell has been initialized. aliases : dict-like, optional Aliases to add after the shell has been initialized. xontribs : iterable of str, optional Xontrib names to load. threadable_predictors : dict-like, optional Threadable predictors to start up with. These overide the defaults. """ ctx = {} if ctx is None else ctx # setup xonsh ctx and execer if not hasattr(builtins, "__xonsh__"): execer = Execer(xonsh_ctx=ctx) builtins.__xonsh__ = XonshSession(ctx=ctx, execer=execer) load_builtins(ctx=ctx, execer=execer) builtins.__xonsh__.shell = Shell(execer, ctx=ctx, shell_type=shell_type) builtins.__xonsh__.env.update(env) install_import_hooks() builtins.aliases.update(aliases) if xontribs: xontribs_load(xontribs) tp = builtins.__xonsh__.commands_cache.threadable_predictors tp.update(threadable_predictors)
def _init_environ(self, ctx, config, rc, scriptcache, cacheall): self.ctx = {} if ctx is None else ctx self.execer = Execer(config=config, login=self.login, xonsh_ctx=self.ctx) self.execer.scriptcache = scriptcache self.execer.cacheall = cacheall if self.stype != 'none' or self.login: # load xontribs from config file names = builtins.__xonsh_config__.get('xontribs', ()) for name in names: xontribs.update_context(name, ctx=self.ctx) # load run control files env = builtins.__xonsh_env__ rc = env.get('XONSHRC') if rc is None else rc self.ctx.update(xonshrc_context(rcfiles=rc, execer=self.execer, initial=self.ctx)) self.ctx['__name__'] = '__main__'
def xonsh_execer(monkeypatch): """Initiate the Execer with a mocked nop `load_builtins`""" monkeypatch.setattr( "xonsh.built_ins.load_builtins.__code__", (lambda *args, **kwargs: None).__code__, ) added_session = False if not hasattr(builtins, "__xonsh__"): added_session = True ensure_attached_session(monkeypatch, XonshSession()) execer = Execer(unload=False) builtins.__xonsh__.execer = execer yield execer if added_session: monkeypatch.delattr(builtins, "__xonsh__", raising=False)
def __init__(self, completekey='tab', stdin=None, stdout=None, ctx=None): super(Shell, self).__init__(completekey=completekey, stdin=stdin, stdout=stdout) self.execer = Execer() env = builtins.__xonsh_env__ if ctx is not None: self.ctx = ctx else: rc = env.get('XONSHRC', None) self.ctx = xonshrc_context(rcfile=rc, execer=self.execer) self.ctx['__name__'] = '__main__' self.completer = Completer() self.buffer = [] self.need_more_lines = False self.mlprompt = None setup_readline()
def create(cls) -> "Shell": import signal from xonsh.built_ins import load_builtins from xonsh.built_ins import XonshSession from xonsh.imphooks import install_import_hooks from xonsh.main import _pprint_displayhook from xonsh.xontribs import xontribs_load import xonsh.history.main as xhm ctx: Dict[str, Any] = {} execer = Execer(xonsh_ctx=ctx) builtins.__xonsh__ = XonshSession(ctx=ctx, execer=execer) # type: ignore load_builtins(ctx=ctx, execer=execer) env = builtins.__xonsh__.env # type: ignore env.update({"XONSH_INTERACTIVE": True, "SHELL_TYPE": "prompt_toolkit"}) builtins.__xonsh__.history = xhm.construct_history( # type: ignore env=env.detype(), ts=[time.time(), None], locked=True) builtins.__xonsh__.history.gc.wait_for_shell = False # type: ignore setattr(sys, "displayhook", _pprint_displayhook) install_import_hooks() builtins.aliases.update({"ll": "ls -alF"}) # type: ignore xontribs_load([""]) def func_sig_ttin_ttou(n: Any, f: Any) -> None: pass signal.signal(signal.SIGTTIN, func_sig_ttin_ttou) signal.signal(signal.SIGTTOU, func_sig_ttin_ttou) shell = cls(execer) builtins.__xonsh__.shell = shell # type: ignore builtins.__xonsh__.shell.shell = shell # type: ignore return shell
def setup(ctx=None, shell_type='none', env=(('RAISE_SUBPROC_ERROR', True),), aliases=(), xontribs=(), threadable_predictors=()): """Starts up a new xonsh shell. Calling this in function in another packages __init__.py will allow xonsh to be fully used in the package in headless or headed mode. This function is primarily indended to make starting up xonsh for 3rd party packages easier. Parameters ---------- ctx : dict-like or None, optional The xonsh context to start with. If None, an empty dictionary is provided. shell_type : str, optional The type of shell to start. By default this is 'none', indicating we should start in headless mode. env : dict-like, optional Environment to update the current environment with after the shell has been initialized. aliases : dict-like, optional Aliases to add after the shell has been initialized. xontribs : iterable of str, optional Xontrib names to load. threadable_predictors : dict-like, optional Threadable predictors to start up with. These overide the defaults. """ ctx = {} if ctx is None else ctx # setup xonsh ctx and execer builtins.__xonsh_ctx__ = ctx builtins.__xonsh_execer__ = Execer(xonsh_ctx=ctx) builtins.__xonsh_shell__ = Shell(builtins.__xonsh_execer__, ctx=ctx, shell_type=shell_type) builtins.__xonsh_env__.update(env) install_import_hooks() builtins.aliases.update(aliases) if xontribs: xontribs_load(xontribs) tp = builtins.__xonsh_commands_cache__.threadable_predictors tp.update(threadable_predictors)
class Shell(Cmd): """The xonsh shell.""" def __init__(self, completekey='tab', stdin=None, stdout=None, ctx=None): super(Shell, self).__init__(completekey=completekey, stdin=stdin, stdout=stdout) self.execer = Execer() env = builtins.__xonsh_env__ if ctx is not None: self.ctx = ctx else: rc = env.get('XONSHRC', None) self.ctx = xonshrc_context(rcfile=rc, execer=self.execer) builtins.__xonsh_ctx__ = self.ctx self.ctx['__name__'] = '__main__' self.completer = Completer() self.buffer = [] self.stdout = StringIO() self.stderr = StringIO() self.last = "" self.need_more_lines = False self.mlprompt = None setup_readline() def __del__(self): teardown_readline() def emptyline(self): """Called when an empty line has been entered.""" self.need_more_lines = False self.default('') def parseline(self, line): """Overridden to no-op.""" return '', line, line def precmd(self, line): return line if self.need_more_lines else line.lstrip() def default(self, line): """Implements code execution.""" line = line if line.endswith('\n') else line + '\n' code = self.push(line) if code is None: return try: # Temporarily redirect stdout and stderr to save results in # history. with redirect_stdout(self.stdout), redirect_stderr(self.stderr): self.execer.exec(code, mode='single', glbs=self.ctx) # no locals self.stdout.seek(0) self.stderr.seek(0) sys.stdout.write(self.stdout.read()) sys.stderr.write(self.stderr.read()) cmd = {} cmd['cmd'] = self.last self.stdout.seek(0) cmd['stdout'] = self.stdout.read() self.stderr.seek(0) cmd['stderr'] = self.stderr.read() self.stdout.seek(0) self.stdout.truncate() self.stderr.seek(0) self.stderr.truncate() builtins.__history__.add(cmd) except XonshError as e: print(e.args[0], file=sys.stderr, end='') except: traceback.print_exc() if builtins.__xonsh_exit__: return True def push(self, line): """Pushes a line onto the buffer and compiles the code in a way that enables multiline input. """ code = None self.buffer.append(line) if self.need_more_lines: return code src = ''.join(self.buffer) try: code = self.execer.compile(src, mode='single', glbs=None, locs=self.ctx) self.last = ''.join(filter(lambda x: x != '\n', self.buffer)) self.reset_buffer() except SyntaxError: if line == '\n': self.reset_buffer() traceback.print_exc() return None self.need_more_lines = True return code def reset_buffer(self): """Resets the line buffer.""" self.buffer.clear() self.need_more_lines = False self.mlprompt = None def completedefault(self, text, line, begidx, endidx): """Implements tab-completion for text.""" rl_completion_suppress_append() # this needs to be called each time return self.completer.complete(text, line, begidx, endidx, ctx=self.ctx) # tab complete on first index too completenames = completedefault def cmdloop(self, intro=None): while not builtins.__xonsh_exit__: try: super(Shell, self).cmdloop(intro=intro) except KeyboardInterrupt: print() # Gives a newline self.reset_buffer() intro = None builtins.__history__.close_history() def settitle(self): env = builtins.__xonsh_env__ term = env.get('TERM', None) if term is None or term == 'linux': return if 'TITLE' in env: t = env['TITLE'] else: return t = format_prompt(t) sys.stdout.write("\x1b]2;{0}\x07".format(t)) @property def prompt(self): """Obtains the current prompt string.""" global RL_LIB, RL_CAN_RESIZE if RL_CAN_RESIZE: # This is needed to support some system where line-wrapping doesn't # work. This is a bug in upstream Python, or possibly readline. RL_LIB.rl_reset_screen_size() if self.need_more_lines: if self.mlprompt is None: self.mlprompt = multiline_prompt() return self.mlprompt env = builtins.__xonsh_env__ if 'PROMPT' in env: p = env['PROMPT'] p = format_prompt(p) else: p = "set '$PROMPT = ...' $ " self.settitle() return p
import builtins # setup xonsh ctx and execer builtins.__xonsh_ctx__ = {} from xonsh.execer import Execer builtins.__xonsh_execer__ = Execer(xonsh_ctx=builtins.__xonsh_ctx__) from xonsh.shell import Shell builtins.__xonsh_shell__ = Shell(builtins.__xonsh_execer__, ctx=builtins.__xonsh_ctx__, shell_type='none') builtins.__xonsh_env__['RAISE_SUBPROC_ERROR'] = True # setup import hooks import xonsh.imphooks xonsh.imphooks.install_import_hooks() __version__ = '0.2.5' del xonsh, builtins, Execer, Shell
def setup(): # only setup one parser global EXECER EXECER = Execer(debug_level=DEBUG_LEVEL)
def execer_setup(): # only setup one parser global EXECER if EXECER is None: EXECER = Execer(debug_level=DEBUG_LEVEL, login=False)
def setup(): global LOADED_HERE if built_ins.BUILTINS_LOADED: unload_builtins() # make sure we have a clean env from other tests. load_builtins(execer=Execer()) LOADED_HERE = True