evanescent /ˌɛvəˈnɛsənt/ (adjective):I find it useful to pass code snippets directly to python while on the command line or from within a shell script. Here are some example one liners you can cut & paste to your command shell to try out.
- vanishing; fading away; fleeting.
- tending to become imperceptible; scarcely perceptible.
Command | Description |
python -c "import this" | Display some python wisdom |
python -c "from __future__ import braces" | Are {} being introduced? |
python -c "import heapq; print heapq.__about__" | An example of included nuggets of info |
math and number formatting | |
python -c "print '%.f' % 1.2E12" | Parse scientific notation and display as integer |
python -c "print 2**1234" | Arbitrary precision integer calculator |
python -c "from decimal import *; d=Decimal('2.0'); print d**1234" | Arbitrary precision floating point |
python -c "import sys; print sum(int(line) for line in sys.stdin)" | Efficiently add integers from stdin |
python -c "print reduce(__import__('operator').add, range(1,101))" | Alternative method to sum a list |
python -c "print sum(1.0/(2<<n) for n in range(10))" | Sum a series |
information lookup | |
python -c "import os; print '\n'.join(os.environ['PATH'].split(os.pathsep))" | Display the $PATH, one per line |
python -c "import os; print os.strerror(42)" | Lookup an error code |
python -c "import platform; print platform.node()" | Print the hostname |
python -c "import httplib,pprint; pprint.pprint(httplib.responses.items())" | Display a dictionary; e.g. HTTP responses |
python -c "import unicodedata as ud; print ud.name(unichr(0x2028))" | Unicode character lookup |
useful modules | |
python -m calendar | Display a calendar |
python -m SimpleHTTPServer | Serve current dir at http://$HOSTNAME:8000/ |
python -m timeit -h | time snippets of code |
There are various techniques, and even an online tool for making arbitrarily sophisticated python one liners, but I wouldn't advise obfuscating something sophisticated into a single line, unless it fits naturally. As an interim step to creating an independent python script, you may find something like funcpy or pyline useful. Also the snippets don't have to be resticted to one line and can be expanded as in this example:
python -c " import os for e in range(128): print '%d\t%s' % (e, os.strerror(e)) " | grep -Fi supportedNote you may balk at the overhead of starting another interpreter, but I find python caches well, and there are speedup options if required. Another place I enter small/temporary pieces of python code is at the python interactive prompt, which I have enhanced with a small wrapper script called inpy to add tab completion and an
lsfunction with globbing.
© Apr 15 2009