December 10th 2014

Starting IPython automatically from zsh

Instead of a calculator, I tend to use IPython for those quotidian bits of "mental" arithmetic:

In  [1]: 17 * 22.2
Out [1]: 377.4

However, I often forget to actually start IPython, resulting in me running the following in my shell:

$ 17 * 22.2
zsh: command not found: 17

Whilst I could learn do this maths within Zsh itself, I would prefer to dump myself into IPython instead — being able to use "_" and Python modules generally is just too useful.

After following this pattern too many times, I put together the following snippet that will detect whether I have prematurely attempted a calculation inside zsh and pretend that I ran it in IPython all along:

zmodload zsh/pcre

math_regex='^[\d\-][\d\.\s\+\*\/\-]*$'

function math_precmd() {
    if [ "${?}" = 0 ]
    then
        return
    fi

    if [ -z "${math_command}" ]
    then
        return
    fi

    if whence -- "$math_command" 2>&1 >/dev/null
    then
        return
    fi

    if [ "${math_command}" -pcre-match "${math_regex}" ]
    then
        echo
        ipython -i -c "_=${math_command}; print _"
    fi
}

function math_preexec() {
    typeset -g math_command="${1}"
}

typeset -ga precmd_functions
typeset -ga preexec_functions

precmd_functions+=math_precmd
preexec_functions+=math_preexec

For example:

lamby@seriouscat:~% 17 * 22.2
zsh: command not found: 17

377.4

In  [1]: _ + 1
Out [1]: 378.4

(Canonical version from my zshrc.d)




You can subscribe to new posts via email or RSS.