response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
``['$XONSH_SYS_CONFIG_DIR/xonshrc', '$XONSH_CONFIG_DIR/xonsh/rc.xsh', '~/.xonshrc']``
def default_xonshrc(env) -> "tuple[str, ...]": """ ``['$XONSH_SYS_CONFIG_DIR/xonshrc', '$XONSH_CONFIG_DIR/xonsh/rc.xsh', '~/.xonshrc']`` """ dxrc = ( os.path.join(xonsh_sys_config_dir(env), "xonshrc"), os.path.join(xonsh_config_dir(env), "rc.xsh"), os.path.expanduser("~/.xonshrc...
``['$XONSH_SYS_CONFIG_DIR/rc.d', '$XONSH_CONFIG_DIR/rc.d']``
def default_xonshrcdir(env): """``['$XONSH_SYS_CONFIG_DIR/rc.d', '$XONSH_CONFIG_DIR/rc.d']``\n""" return get_config_paths(env, "rc.d")
By default, the following paths are searched. 1. ``$XONSH_CONFIG_DIR/completions`` - user level completions 2. ``$XONSH_SYS_CONFIG_DIR/completions`` - system level completions 3. ``$XONSH_DATA_DIR/generated_completions`` - auto generated completers from man pages 4. ``$XDG_DATA_DIRS/xonsh/vendor_completions`` - complet...
def default_completer_dirs(env): """By default, the following paths are searched. 1. ``$XONSH_CONFIG_DIR/completions`` - user level completions 2. ``$XONSH_SYS_CONFIG_DIR/completions`` - system level completions 3. ``$XONSH_DATA_DIR/generated_completions`` - auto generated completers from man pages ...
Appends a newline if we are in interactive mode
def xonsh_append_newline(env): """Appends a newline if we are in interactive mode""" return env.get("XONSH_INTERACTIVE", False)
Gets a default instanse of LsColors
def default_lscolors(env): """Gets a default instanse of LsColors""" inherited_lscolors = os_environ.get("LS_COLORS", None) if inherited_lscolors is None: lsc = LsColors.fromdircolors() else: lsc = LsColors.fromstring(inherited_lscolors) # have to place this in the env, so it is app...
``xonsh.prompt.PROMPT_FIELDS``
def default_prompt_fields(env): """``xonsh.prompt.PROMPT_FIELDS``""" # todo: generate document for all default fields return prompt.PromptFields(XSH)
Locates an executable on the file system.
def locate_binary(name): """Locates an executable on the file system.""" return XSH.commands_cache.locate_binary(name)
Attempts to read in all xonshrc files (and search xonshrc directories), and returns the list of rc file paths successfully loaded, in the order of loading.
def xonshrc_context( rcfiles=None, rcdirs=None, execer=None, ctx=None, env=None, login=True ): """ Attempts to read in all xonshrc files (and search xonshrc directories), and returns the list of rc file paths successfully loaded, in the order of loading. """ loaded = [] ctx = {} if ctx i...
Environment fixes for Windows. Operates in-place.
def windows_foreign_env_fixes(ctx): """Environment fixes for Windows. Operates in-place.""" # remove these bash variables which only cause problems. for ev in ["HOME", "OLDPWD"]: if ev in ctx: del ctx[ev] # Override path-related bash variables; on Windows bash uses # /c/Windows/...
Environment fixes for all operating systems
def foreign_env_fixes(ctx): """Environment fixes for all operating systems""" if "PROMPT" in ctx: del ctx["PROMPT"]
Loads a xonsh file and applies it as a run control. Any exceptions are logged here, returns boolean indicating success.
def xonsh_script_run_control(filename, ctx, env, execer=None, login=True): """Loads a xonsh file and applies it as a run control. Any exceptions are logged here, returns boolean indicating success. """ if execer is None: return False updates = {"__file__": filename, "__name__": os.path.abspa...
Constructs a default xonsh environment.
def default_env(env=None): """Constructs a default xonsh environment.""" # in order of increasing precedence ctx = { "BASH_COMPLETIONS": list(DEFAULT_VARS["BASH_COMPLETIONS"].default), "PROMPT_FIELDS": DEFAULT_VARS["PROMPT_FIELDS"].default(env), "XONSH_VERSION": XONSH_VERSION, } ...
Makes a dictionary containing the $ARGS and $ARG<N> environment variables. If the supplied ARGS is None, then sys.argv is used.
def make_args_env(args=None): """Makes a dictionary containing the $ARGS and $ARG<N> environment variables. If the supplied ARGS is None, then sys.argv is used. """ if args is None: args = sys.argv env = {"ARG" + str(i): arg for i, arg in enumerate(args)} env["ARGS"] = list(args) # make...
Extracts data from a foreign (non-xonsh) shells. Currently this gets the environment, aliases, and functions but may be extended in the future. Parameters ---------- shell : str The name of the shell, such as 'bash' or '/bin/sh'. interactive : bool, optional Whether the shell should be run in interactive mode....
def foreign_shell_data( shell, interactive=True, login=False, envcmd=None, aliascmd=None, extra_args=(), currenv=None, safe=True, prevcmd="", postcmd="", funcscmd=None, sourcer=None, use_tmpfile=False, tmpfile_ext=None, runcmd=None, seterrprevcmd=None, ...
Parses the environment portion of string into a dict.
def parse_env(s): """Parses the environment portion of string into a dict.""" m = ENV_RE.search(s) if m is None: return {} g1 = m.group(1) g1 = g1[:-1] if g1.endswith("\n") else g1 env = dict(ENV_SPLIT_RE.findall(g1)) return env
Parses the aliases portion of string into a dict.
def parse_aliases(s, shell, sourcer=None, files=(), extra_args=()): """Parses the aliases portion of string into a dict.""" m = ALIAS_RE.search(s) if m is None: return {} g1 = m.group(1) g1 = g1.replace("\\\n", " ") items = [ line.split("=", 1) for line in g1.splitlines()...
Parses the funcs portion of a string into a dict of callable foreign function wrappers.
def parse_funcs(s, shell, sourcer=None, files=(), extra_args=()): """Parses the funcs portion of a string into a dict of callable foreign function wrappers. """ m = FUNCS_RE.search(s) if m is None: return {} g1 = m.group(1) if ON_WINDOWS: g1 = g1.replace(os.sep, os.altsep) ...
Ensures that a mapping follows the shell specification.
def ensure_shell(shell): """Ensures that a mapping follows the shell specification.""" if not isinstance(shell, cabc.MutableMapping): shell = dict(shell) shell_keys = set(shell.keys()) if not (shell_keys <= VALID_SHELL_PARAMS): raise KeyError(f"unknown shell keys: {shell_keys - VALID_SH...
Loads environments from foreign shells. Parameters ---------- shells : sequence of dicts An iterable of dicts that can be passed into foreign_shell_data() as keyword arguments. Returns ------- env : dict A dictionary of the merged environments.
def load_foreign_envs(shells): """Loads environments from foreign shells. Parameters ---------- shells : sequence of dicts An iterable of dicts that can be passed into foreign_shell_data() as keyword arguments. Returns ------- env : dict A dictionary of the merged e...
Loads aliases from foreign shells. Parameters ---------- shells : sequence of dicts An iterable of dicts that can be passed into foreign_shell_data() as keyword arguments. Returns ------- aliases : dict A dictionary of the merged aliases.
def load_foreign_aliases(shells): """Loads aliases from foreign shells. Parameters ---------- shells : sequence of dicts An iterable of dicts that can be passed into foreign_shell_data() as keyword arguments. Returns ------- aliases : dict A dictionary of the merged...
Finds the source encoding given bytes representing a file by checking a special comment at either the first or second line of the source file. https://docs.python.org/3/howto/unicode.html#unicode-literals-in-python-source-code If no encoding is found, UTF-8 codec with BOM signature will be returned as it skips an optio...
def find_source_encoding(src): """Finds the source encoding given bytes representing a file by checking a special comment at either the first or second line of the source file. https://docs.python.org/3/howto/unicode.html#unicode-literals-in-python-source-code If no encoding is found, UTF-8 codec with B...
Figures out if we should dispatch to a load event
def _should_dispatch_xonsh_import_event_loader(): """Figures out if we should dispatch to a load event""" return ( len(events.on_import_pre_create_module) > 0 or len(events.on_import_post_create_module) > 0 or len(events.on_import_pre_exec_module) > 0 or len(events.on_import_post...
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.
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_NO...
Make an object info dict with all fields present.
def object_info(**kw): """Make an object info dict with all fields present.""" infodict = dict(itertools.zip_longest(info_fields, [None])) infodict.update(kw) return infodict
Get encoding for python source file defining obj Returns None if obj is not defined in a sourcefile.
def get_encoding(obj): """Get encoding for python source file defining obj Returns None if obj is not defined in a sourcefile. """ ofile = find_file(obj) # run contents of file through pager starting at line where the object # is defined, as long as the file isn't binary and is actually on the ...
Stable wrapper around inspect.getdoc. This can't crash because of attribute problems. It also attempts to call a getdoc() method on the given object. This allows objects which provide their docstrings via non-standard mechanisms (like Pyro proxies) to still be inspected by ipython's ? system.
def getdoc(obj): """Stable wrapper around inspect.getdoc. This can't crash because of attribute problems. It also attempts to call a getdoc() method on the given object. This allows objects which provide their docstrings via non-standard mechanisms (like Pyro proxies) to still be inspected by ipy...
Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether the object is known to come from a binary source. This implementation will skip returning ...
def getsource(obj, is_binary=False): """Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether the object is known to c...
True if obj is a function ()
def is_simple_callable(obj): """True if obj is a function ()""" return ( inspect.isfunction(obj) or inspect.ismethod(obj) or isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type) )
Wrapper around :func:`inspect.getfullargspec` on Python 3, and :func:inspect.getargspec` on Python 2. In addition to functions and methods, this can also handle objects with a ``__call__`` attribute.
def getargspec(obj): """Wrapper around :func:`inspect.getfullargspec` on Python 3, and :func:inspect.getargspec` on Python 2. In addition to functions and methods, this can also handle objects with a ``__call__`` attribute. """ if safe_hasattr(obj, "__call__") and not is_simple_callable(obj): ...
Format argspect, convenience wrapper around inspect's. This takes a dict instead of ordered arguments and calls inspect.format_argspec with the arguments in the necessary order.
def format_argspec(argspec): """Format argspect, convenience wrapper around inspect's. This takes a dict instead of ordered arguments and calls inspect.format_argspec with the arguments in the necessary order. """ return inspect.formatargspec( argspec["args"], argspec["varargs"], argspec["v...
Extract call tip data from an oinfo dict. Parameters ---------- oinfo : dict format_call : bool, optional If True, the call line is formatted and returned as a string. If not, a tuple of (name, argspec) is returned. Returns ------- call_info : None, str or (str, dict) tuple. When format_call is True, the...
def call_tip(oinfo, format_call=True): """Extract call tip data from an oinfo dict. Parameters ---------- oinfo : dict format_call : bool, optional If True, the call line is formatted and returned as a string. If not, a tuple of (name, argspec) is returned. Returns -------...
Find the absolute path to the file where an object was defined. This is essentially a robust wrapper around `inspect.getabsfile`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- fname : str The absolute path to the file where the object was defined.
def find_file(obj): """Find the absolute path to the file where an object was defined. This is essentially a robust wrapper around `inspect.getabsfile`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- fname : str The abs...
Find the line number in a file where an object was defined. This is essentially a robust wrapper around `inspect.getsourcelines`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- lineno : int The line number where the object definition starts.
def find_source_lines(obj): """Find the line number in a file where an object was defined. This is essentially a robust wrapper around `inspect.getsourcelines`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- lineno : int ...
Context manager that replaces a thread's task queue and job dictionary with those of the main thread This allows another thread (e.g. the commands jobs, disown, and bg) to handle the main thread's job control.
def use_main_jobs(): """Context manager that replaces a thread's task queue and job dictionary with those of the main thread This allows another thread (e.g. the commands jobs, disown, and bg) to handle the main thread's job control. """ old_tasks = get_tasks() old_jobs = get_jobs() try...
Safely call wait_for_active_job()
def _safe_wait_for_active_job(last_task=None, backgrounded=False): """Safely call wait_for_active_job()""" have_error = True while have_error: try: rtn = wait_for_active_job( last_task=last_task, backgrounded=backgrounded, return_error=True ) except Ch...
Get the next active task and put it on top of the queue
def get_next_task(): """Get the next active task and put it on top of the queue""" tasks = get_tasks() _clear_dead_jobs() selected_task = None for tid in tasks: task = get_task(tid) if not task["bg"] and task["status"] == "running": selected_task = tid break ...
Print a line describing job number ``num``.
def print_one_job(num, outfile=sys.stdout, format="dict"): """Print a line describing job number ``num``.""" info = format_job_string(num, format) if info: print(info, file=outfile)
Get the lowest available unique job number (for the next job created).
def get_next_job_number(): """Get the lowest available unique job number (for the next job created).""" _clear_dead_jobs() i = 1 while i in get_jobs(): i += 1 return i
Add a new job to the jobs dictionary.
def add_job(info): """Add a new job to the jobs dictionary.""" num = get_next_job_number() info["started"] = time.time() info["status"] = "running" get_tasks().appendleft(num) get_jobs()[num] = info if info["bg"] and XSH.env.get("XONSH_INTERACTIVE"): print_one_job(num)
Clean up jobs for exiting shell In non-interactive mode, send SIGHUP to all jobs. In interactive mode, check for suspended or background jobs, print a warning if any exist, and return False. Otherwise, return True.
def clean_jobs(): """Clean up jobs for exiting shell In non-interactive mode, send SIGHUP to all jobs. In interactive mode, check for suspended or background jobs, print a warning if any exist, and return False. Otherwise, return True. """ jobs_clean = True if XSH.env["XONSH_INTERACTIVE"]:...
Send SIGHUP to all child processes (called when exiting xonsh).
def hup_all_jobs(): """ Send SIGHUP to all child processes (called when exiting xonsh). """ _clear_dead_jobs() for job in get_jobs().values(): _hup(job)
xonsh command: jobs Display a list of all current jobs.
def jobs(args, stdin=None, stdout=sys.stdout, stderr=None): """ xonsh command: jobs Display a list of all current jobs. """ _clear_dead_jobs() format = "posix" if "--posix" in args else "dict" for j in get_tasks(): print_one_job(j, outfile=stdout, format=format) return None, Non...
used by fg and bg to resume a job either in the foreground or in the background.
def resume_job(args, wording: tp.Literal["fg", "bg"]): """ used by fg and bg to resume a job either in the foreground or in the background. """ _clear_dead_jobs() tasks = get_tasks() if len(tasks) == 0: return "", "There are currently no suspended jobs" if len(args) == 0: ti...
xonsh command: fg Bring the currently active job to the foreground, or, if a single number is given as an argument, bring that job to the foreground. Additionally, specify "+" for the most recent job and "-" for the second most recent job.
def fg(args, stdin=None): """ xonsh command: fg Bring the currently active job to the foreground, or, if a single number is given as an argument, bring that job to the foreground. Additionally, specify "+" for the most recent job and "-" for the second most recent job. """ return resume_job...
xonsh command: bg Resume execution of the currently active job in the background, or, if a single number is given as an argument, resume that job in the background.
def bg(args, stdin=None): """xonsh command: bg Resume execution of the currently active job in the background, or, if a single number is given as an argument, resume that job in the background. """ res = resume_job(args, wording="bg") if res is None: curtask = get_task(get_tasks()[0]) ...
Return currently running jobs ids
def job_id_completer(xsh, **_): """Return currently running jobs ids""" for job_id in get_jobs(): yield RichCompletion(str(job_id), description=format_job_string(job_id))
Remove the specified jobs from the job table; the shell will no longer report their status, and will not complain if you try to exit an interactive shell with them running or stopped. If the jobs are currently stopped and the $AUTO_CONTINUE option is not set ($AUTO_CONTINUE = False), a warning is printed containing in...
def disown_fn( job_ids: Annotated[ tp.Sequence[int], Arg(type=int, nargs="*", completer=job_id_completer) ], force_auto_continue=False, ): """Remove the specified jobs from the job table; the shell will no longer report their status, and will not complain if you try to exit an interactiv...
JSON serializer for xonsh custom data structures. This is only called when another normal JSON types are not found.
def serialize_xonsh_json(val): """JSON serializer for xonsh custom data structures. This is only called when another normal JSON types are not found. """ return str(val)
Decorator for constructing lazy objects from a function.
def lazyobject(f: tp.Callable[..., RT]) -> RT: """Decorator for constructing lazy objects from a function.""" return LazyObject(f, f.__globals__, f.__name__)
Decorator for constructing lazy dicts from a function.
def lazydict(f): """Decorator for constructing lazy dicts from a function.""" return LazyDict(f, f.__globals__, f.__name__)
Decorator for constructing lazy booleans from a function.
def lazybool(f): """Decorator for constructing lazy booleans from a function.""" return LazyBool(f, f.__globals__, f.__name__)
Entry point for loading modules in background thread. Parameters ---------- name : str Module name to load in background thread. package : str or None, optional Package name, has the same meaning as in importlib.import_module(). debug : str, optional Debugging symbol name to look up in the environment. env...
def load_module_in_background( name, package=None, debug="DEBUG", env=None, replacements=None ): """Entry point for loading modules in background thread. Parameters ---------- name : str Module name to load in background thread. package : str or None, optional Package name, has ...
Creates an index for a JSON file.
def index(obj, sort_keys=False): """Creates an index for a JSON file.""" idx = {} json_obj = _to_json_with_size(obj, sort_keys=sort_keys) s, idx["offsets"], _, idx["sizes"] = json_obj return s, idx
Dumps an object to JSON with an index.
def dumps(obj, sort_keys=False): """Dumps an object to JSON with an index.""" data, idx = index(obj, sort_keys=sort_keys) jdx = json.dumps(idx, sort_keys=sort_keys) iloc = 69 ilen = len(jdx) dloc = iloc + ilen + 11 dlen = len(data) s = JSON_FORMAT.format( index=jdx, data=data, il...
Dumps an object to JSON file.
def ljdump(obj, fp, sort_keys=False): """Dumps an object to JSON file.""" s = dumps(obj, sort_keys=sort_keys) fp.write(s)
Mapping from ``tokenize`` tokens (or token types) to PLY token types. If a simple one-to-one mapping from ``tokenize`` to PLY exists, the lexer will look it up here and generate a single PLY token of the given type. Otherwise, it will fall back to handling that token using one of the handlers in``special_handlers``.
def token_map(): """Mapping from ``tokenize`` tokens (or token types) to PLY token types. If a simple one-to-one mapping from ``tokenize`` to PLY exists, the lexer will look it up here and generate a single PLY token of the given type. Otherwise, it will fall back to handling that token using one of the...
Function for handling name tokens
def handle_name(state, token): """Function for handling name tokens""" typ = "NAME" state["last"] = token needs_whitespace = token.string in NEED_WHITESPACE has_whitespace = needs_whitespace and RE_NEED_WHITESPACE.match( token.line[max(0, token.start[1] - 1) :] ) if state["pymode"][-...
Function for handling ``)``
def handle_rparen(state, token): """ Function for handling ``)`` """ e = _end_delimiter(state, token) if e is None or state["tolerant"]: state["last"] = token yield _new_token("RPAREN", ")", token.start) else: yield _new_token("ERRORTOKEN", e, token.start)
Function for handling ``}``
def handle_rbrace(state, token): """Function for handling ``}``""" e = _end_delimiter(state, token) if e is None or state["tolerant"]: state["last"] = token yield _new_token("RBRACE", "}", token.start) else: yield _new_token("ERRORTOKEN", e, token.start)
Function for handling ``]``
def handle_rbracket(state, token): """ Function for handling ``]`` """ e = _end_delimiter(state, token) if e is None or state["tolerant"]: state["last"] = token yield _new_token("RBRACKET", "]", token.start) else: yield _new_token("ERRORTOKEN", e, token.start)
Function for handling special whitespace characters in subprocess mode
def handle_error_space(state, token): """ Function for handling special whitespace characters in subprocess mode """ if not state["pymode"][-1][0]: state["last"] = token yield _new_token("WS", token.string, token.start) else: yield from []
Function for handling special line continuations as whitespace characters in subprocess mode.
def handle_error_linecont(state, token): """Function for handling special line continuations as whitespace characters in subprocess mode. """ if state["pymode"][-1][0]: return prev = state["last"] if prev.end != token.start: return # previous token is separated by whitespace ...
Function for handling error tokens
def handle_error_token(state, token): """ Function for handling error tokens """ state["last"] = token if token.string == "!": typ = "BANG" elif not state["pymode"][-1][0]: typ = "NAME" else: typ = "ERRORTOKEN" yield _new_token(typ, token.string, token.start)
Function for handling tokens that should be ignored
def handle_ignore(state, token): """Function for handling tokens that should be ignored""" yield from []
Mapping from ``tokenize`` tokens (or token types) to the proper function for generating PLY tokens from them. In addition to yielding PLY tokens, these functions may manipulate the Lexer's state.
def special_handlers(): """Mapping from ``tokenize`` tokens (or token types) to the proper function for generating PLY tokens from them. In addition to yielding PLY tokens, these functions may manipulate the Lexer's state. """ sh = { NL: handle_ignore, COMMENT: handle_ignore, ...
General-purpose token handler. Makes use of ``token_map`` or ``special_map`` to yield one or more PLY tokens from the given input. Parameters ---------- state The current state of the lexer, including information about whether we are in Python mode or subprocess mode, which changes the lexer's behavior. ...
def handle_token(state, token): """ General-purpose token handler. Makes use of ``token_map`` or ``special_map`` to yield one or more PLY tokens from the given input. Parameters ---------- state The current state of the lexer, including information about whether we are in Pytho...
Given a string containing xonsh code, generates a stream of relevant PLY tokens using ``handle_token``.
def get_tokens(s, tolerant, pymode=True, tokenize_ioredirects=True): """ Given a string containing xonsh code, generates a stream of relevant PLY tokens using ``handle_token``. """ state = { "indents": [0], "last": None, "pymode": [(pymode, "", "", (0, 0))], "stream":...
Gets a sysctl value by name. If return_str is true, this will return a string representation, else it will return the raw value.
def sysctlbyname(name, return_str=True): """Gets a sysctl value by name. If return_str is true, this will return a string representation, else it will return the raw value. """ # forked from https://gist.github.com/pudquick/581a71425439f2cf8f09 size = c_uint(0) # Find out how big our buffer will...
Proxy function for loading process title
def get_setproctitle(): """Proxy function for loading process title""" try: from setproctitle import setproctitle as spt except ImportError: return return spt
Return a path only if the path is actually legal (file or directory) This is very similar to argparse.FileType, except that it doesn't return an open file handle, but rather simply validates the path.
def path_argument(s): """Return a path only if the path is actually legal (file or directory) This is very similar to argparse.FileType, except that it doesn't return an open file handle, but rather simply validates the path.""" s = os.path.abspath(os.path.expanduser(s)) if not os.path.exists(s): ...
Starts up the essential services in the proper order. This returns the environment instance as a convenience.
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 = ...
Setup for main xonsh entry point. Returns parsed arguments.
def premain(argv=None): """Setup for main xonsh entry point. Returns parsed arguments.""" if argv is None: argv = sys.argv[1:] setup_timings(argv) setproctitle = get_setproctitle() if setproctitle is not None: setproctitle(" ".join(["xonsh"] + argv)) args = parser.parse_args(arg...
Main entry point for xonsh cli.
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...
Teardown for main xonsh entry point, accepts parsed arguments.
def postmain(args=None): """Teardown for main xonsh entry point, accepts parsed arguments.""" XSH.unload() XSH.shell = None
Generator that runs pre- and post-main() functions. This has two iterations. The first yields the shell. The second returns None but cleans up the shell.
def main_context(argv=None): """Generator that runs pre- and post-main() functions. This has two iterations. The first yields the shell. The second returns None but cleans up the shell. """ args = premain(argv) yield XSH.shell postmain(args)
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__.p...
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 headles...
Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffer or a string containing the source code.
def source_to_unicode(txt, errors="replace", skip_encoding_cookie=True): """Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buff...
Generator to pull lines from a text-mode file, skipping the encoding cookie if it is found in the first two lines.
def strip_encoding_cookie(filelike): """Generator to pull lines from a text-mode file, skipping the encoding cookie if it is found in the first two lines. """ it = iter(filelike) try: first = next(it) if not cookie_comment_re.match(first): yield first second = nex...
Read a Python file, using the encoding declared inside the file. Parameters ---------- filename : str The path to the file to read. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output - compiling a u...
def read_py_file(filename, skip_encoding_cookie=True): """Read a Python file, using the encoding declared inside the file. Parameters ---------- filename : str The path to the file to read. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in t...
Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are the same as for bytes.decode(), but here 'replace' is the default. skip_encoding_cookie : boo...
def read_py_url(url, errors="replace", skip_encoding_cookie=True): """Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are...
Given a list, returns a readline() function that returns the next element with each call.
def _list_readline(x): """Given a list, returns a readline() function that returns the next element with each call. """ x = iter(x) def readline(): return next(x) return readline
``True`` if on a BSD operating system, else ``False``.
def ON_BSD(): """``True`` if on a BSD operating system, else ``False``.""" return bool(ON_FREEBSD) or bool(ON_NETBSD) or bool(ON_OPENBSD) or bool(ON_DRAGONFLY)
True if we are on BeOS or Haiku.
def ON_BEOS(): """True if we are on BeOS or Haiku.""" return sys.platform == "beos5" or sys.platform == "haiku1"
True if we are on Windows Subsystem for Linux (WSL)
def ON_WSL(): """True if we are on Windows Subsystem for Linux (WSL)""" return "microsoft" in platform.release()
The python version info tuple in a canonical bytes form.
def PYTHON_VERSION_INFO_BYTES(): """The python version info tuple in a canonical bytes form.""" return ".".join(map(str, sys.version_info)).encode()
``True`` if `pygments` is available, else ``False``.
def HAS_PYGMENTS(): """``True`` if `pygments` is available, else ``False``.""" spec = importlib.util.find_spec("pygments") return spec is not None
pygments.__version__ version if available, else None.
def pygments_version(): """pygments.__version__ version if available, else None.""" if HAS_PYGMENTS: import pygments v = pygments.__version__ else: v = None return v
Returns `pygments`'s version as tuple of integers.
def pygments_version_info(): """Returns `pygments`'s version as tuple of integers.""" if HAS_PYGMENTS: return tuple(int(x) for x in pygments_version().strip("<>+-=.").split(".")) else: return None
Tests if the `prompt_toolkit` is available.
def has_prompt_toolkit(): """Tests if the `prompt_toolkit` is available.""" spec = importlib.util.find_spec("prompt_toolkit") return spec is not None
Returns `prompt_toolkit.__version__` if available, else ``None``.
def ptk_version(): """Returns `prompt_toolkit.__version__` if available, else ``None``.""" if has_prompt_toolkit(): import prompt_toolkit return getattr(prompt_toolkit, "__version__", "<0.57") else: return None
Returns `prompt_toolkit`'s version as tuple of integers.
def ptk_version_info(): """Returns `prompt_toolkit`'s version as tuple of integers.""" if has_prompt_toolkit(): return tuple(int(x) for x in ptk_version().strip("<>+-=.").split(".")) else: return None
Checks if readline is available to import.
def is_readline_available(): """Checks if readline is available to import.""" spec = importlib.util.find_spec("readline") return spec is not None
String of all path separators.
def seps(): """String of all path separators.""" s = os.path.sep if os.path.altsep is not None: s += os.path.altsep return s
This is a safe version of os.path.split(), which does not work on input without a drive.
def pathsplit(p): """This is a safe version of os.path.split(), which does not work on input without a drive. """ n = len(p) if n == 0: # lazy object seps does not get initialized when n is zero return "", "" while n and p[n - 1] not in seps: n -= 1 pre = p[:n] pr...
This is a safe version of os.path.basename(), which does not work on input without a drive. This version does.
def pathbasename(p): """This is a safe version of os.path.basename(), which does not work on input without a drive. This version does. """ return pathsplit(p)[-1]
Dispatches to the correct platform-dependent expanduser() function.
def expanduser(): """Dispatches to the correct platform-dependent expanduser() function.""" if ON_WINDOWS: return windows_expanduser else: return os.path.expanduser
A Windows-specific expanduser() function for xonsh. This is needed since os.path.expanduser() does not check on Windows if the user actually exists. This restricts expanding the '~' if it is not followed by a separator. That is only '~/' and '~' are expanded.
def windows_expanduser(path): """A Windows-specific expanduser() function for xonsh. This is needed since os.path.expanduser() does not check on Windows if the user actually exists. This restricts expanding the '~' if it is not followed by a separator. That is only '~/' and '~\' are expanded. """ ...
Returns a tuple contains two strings: the hash and the date.
def githash(): """Returns a tuple contains two strings: the hash and the date.""" install_base = os.path.dirname(__file__) githash_file = f"{install_base}/dev.githash" if not os.path.exists(githash_file): return None, None sha = None date_ = None try: with open(githash_file) ...
The id of the Linux distribution running on, possibly 'unknown'. None on non-Linux platforms.
def linux_distro(): """The id of the Linux distribution running on, possibly 'unknown'. None on non-Linux platforms. """ if ON_LINUX: if distro: ld = distro.id() elif PYTHON_VERSION_INFO < (3, 6, 6): ld = platform.linux_distribution()[0] or "unknown" ...
Returns the path to git for windows, if available and None otherwise.
def git_for_windows_path(): """Returns the path to git for windows, if available and None otherwise.""" import winreg try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\GitForWindows") gfwp, _ = winreg.QueryValueEx(key, "InstallPath") except FileNotFoundError: gfwp ...