A Bash function and alias combo that lets you evaluate simple Python expressions from the Bash command-line:
The function and alias combo is necessary to prevent Bash from expanding wildcard expressions like * and ? and such. I borrowed the so-called “magic aliases” technique from Simon Tatham’s “Magic Aliases: A Layering Loophole in the Bourne Shell”. Even so, I have not found a way to get Bash to not parse out quotes and redirection characters and what not so some stuff works as expected and some stuff doesn’t.
$ pyval 23 * 2 46 $ pyval 0x20 * 2 64 $ pyval [2 * x for x in [1, 2, 3]] [2, 4, 6]
Characters like < and > get parsed by Bash as redirections. You can stop this by quoting:
$ pyval 1 < 2 -bash: 2: No such file or directory $ pyval '1 < 2' True $ pyval '1 << 5' 32
I have not found a way to stop Bash from parsing out quotes so that unfortunately you have to do this ugly double quoting of string literals:
$ pyval 'hello' Traceback (most recent call last): File "", line 1, in NameError: name 'hello' is not defined $ pyval "'hello'.upper()" HELLO $ pyval 72 * "'-'" ------------------------------------------------------------------------
Just for fun:
$ pyval "' '.join([word.capitalize() for word in 'the green mile'.capitalize().split()])" The Green Mile
Unfortunately, this simple implementation doesn’t let you import Python modules. I could imagine a way to rewrite this so that you could specify modules to import as arguments, but I don’t know if it’s worth it. After all, it’s not that hard to type “python” and if you really want a pythonic shell, you could use ipython with the so-called “Sh profile” (which I’ve never got into the habit of).