Merge Python and shell in xonsh
xonsh, pronounced conch, is a wonderful shell-Python mixed execution environment, where you can execute shell commands and Python codes equally and interchangeably.
Installation
xonsh can be installed at system-level with /usr/bin/pip3 install 'xonsh[full]'. If there’s no system-level pip (/usr/bin/pip3) installed, you can install it with apt install python3-pip on Debain-based Linux.
However, for support of some critical tools (such as fzf, autojump) are still not mature, system-level Python is not a good idea in most cases. The recommended way is used as a on-site REPL and script-execution engine in a Python project. You can embed it into you Poetry defined project as follows:
pipx install poetry
poetry new <my-project-name>
cd <my-project-name>
poetry env use <python-name/path>
poetry add 'xonsh[full]'
poetry run xonsh
Configurations
Prompt, Aliases and Plugins
In most cases, the path of your user-level rc file (run control file) is ~/.config/xonsh/rc.xsh. Customize prompt with $PROMPT = .... Define aliases with aliases['<alias-name>'] = '<shell-command>'. Install plugins with xontrib load <plugin-name>. Note that you need install the plugin with pip beforehand. Here is an example:
cat << EOF > ~/.config/xonsh/rc.xsh
$PROMPT = '{YELLOW}{env_name}{BLUE}{user}@{hostname}:{GREEN}{cwd} {ITALIC_YELLOW}{gitstatus} {RESET}\n> '
$RIGHT_PROMPT = '{localtime}'
$AUTO_CD = True
xontrib load hist_navigator
aliases['ddp'] = 'dotdrop'
aliases['ga'] = 'git add -A'
aliases['gci'] = 'git commit'
aliases['gco'] = 'git checkout'
aliases['gd'] = 'git diff'
aliases['gl'] = 'git log '
aliases['glg'] = "git log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%ai%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all"
aliases['gs'] = 'git status'
aliases['l'] = 'ls -la'
aliases['ll'] = 'ls -lh'
aliases['lt'] = 'ls -lt'
aliases['ltr'] = 'ls -ltr'
aliases['ta'] = 'tmux attach -t'
aliases['tl'] = 'tmux ls'
aliases['tn'] = 'tmux new -A -s'
aliases['vi'] = "python3 ~/.config/nvim/vi"
EOF
See Run Control File for more details.
Color Theme
You can list installed themes, and customize the colors of texts, numbers,
punctuation marks with:
xonfig styles
$XONSH_COLOR_STYLE='paraiso-dark'
See change the current color theme
for more details.
Enhanced Python REPL
When exploring data with Python, we constantly print value of a variable,
plot (part of) a dataframe, etc. This is a perfect scenario for REPL.
Compared with IPython, xonsh has better support with shell commands and
history command auto-completion.
In a xonsh shell, use source to load all variables into the current session:
source <my-script.xsh>
Comments
Post a Comment