forked from lowks/pythonpy
-
Notifications
You must be signed in to change notification settings - Fork 0
More Examples
Russell Stewart edited this page Mar 23, 2015
·
53 revisions
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.
Here's one use I have of the (-C) flag for my pyplt alias:
alias pyplt='py -c '"'"'matplotlib.use(`Agg`); from matplotlib import pyplot as plt'"'"' -C '"'"'plt.savefig("output.jpg")'"'"
Which isn't pretty, but allows one to plot command line data as follows:
py '[math.sin(x/10) for x in range(100)]' | pyplt -l 'plt.plot(l)'Fig1. - output.jpg
Pythonpy makes it easy to manipulate json using python's built in json library. Note you can always get raw access to stdin using sys.stdin.
$ curl http://stewart.guru/s/employees.json | py '[json.load(sys.stdin)]'
{u'employees': [{u'lastName': u'Doe', u'firstName': u'John'}, {u'lastName': u'Smith', u'firstName': u'Anna'}, {u'lastName': u'Jones', u'firstName': u'Peter'}]}
$ curl http://stewart.guru/s/employees.json | py 'json.load(sys.stdin)["employees"][0]["firstName"]' John
The following downloads all the images from the front page of imgur with beautifulsoup installed:
curl http://imgur.com/ | py 'map(lambda _: _.attrs["src"].partition("//")[-1], bs4.BeautifulSoup(sys.stdin).findAll("img"))' | xargs -n1 wget >/dev/null 2>&1