Skip to content
Sindhu S edited this page Jan 11, 2015 · 53 revisions

Pythonpy will automatically replace sharp quotes with single quotes before processing an expression:

py '`hello world`'
hello world
py '"ma`am"'
ma'am

Run a statement as you would using python -c with py -c:

py -c 'a = 5; print(`a`)'
a

Alternatively:

py -c 'a = 5' 'a'
5

The argument of (-c) will run before the expression. In the rarer case that you need to run a statement after the main expression, you can use the (-C) flag.
Plot data you have access to from the command line using the pyplt alias:

alias pyplt='py -c '"'"'matplotlib.use(`Agg`); from matplotlib import pyplot as plt'"'"' -C '"'"'plt.savefig("output.jpg")'"'"
py '[math.sin(x/10) for x in range(100)]' | pyplt -l 'plt.plot(l)'
Fig1. - output.jpg

Often you only care about one section of a long row. Splitting the input can help you get that part:

echo 'a,b,c' | py --split_input , -x 'x'
['a', 'b', 'c']
echo 'a,b,c' | py --si , -x 'x[1]'
b
echo 'a b  c.' | py --si ' *' -x 'x[-1]'
c.

You can split the output when you're done as well:

echo 'a,b,c' | py --si , -x x --so ' '
a b c
echo 'a,b,c' | py --si , -x x --so $'\t'
a    b    c
echo 'a   b c' | py --si ' *' -x x --so $'\n'
a
b
c

Note that the $ in $'\n' is necessary to pass raw strings in bash. See here for discussion.
Pythonpy can also preprocess and postprocess inputs in json format.

echo '13' | py --ji -x 'x*7'
91
echo '{"foo": "lorem", "bar": "ipsum"}' | py --ji -x 'x[`foo`]'
lorem
py 'range(4)' | py --ji -l 'sum(l)'
6

This can also work well for constructing json:

py '[{chr(i+ord(`a`)):i for i in range(26)}]' --jo
{"a": 0, "c": 2, "b": 1, "e": 4, "d": 3, "g": 6, "f": 5, "i": 8, "h": 7, "k": 10,
 "j": 9, "m": 12, "l": 11, "o": 14, "n": 13, "q": 16, "p": 15, "s": 18, "r": 17,
 "u": 20, "t": 19, "w": 22, "v": 21, "y": 24, "x": 23, "z": 25}

Clone this wiki locally