Python
@Python
.. TODO - ConfigParser
.. TODO - gdchart
.. TODO - asyncore/asynchat
.. TODO - shlex
.. TODO - paramiko
.. TODO - threading, multiprocessing
Essential third-party tools
Getopts
.. code-block:: python
import getopt, sys
try:
print str(err)
sys.exit(1)
Opening a file
.. code-block:: python
try:
Syntax cheatsheet
.. code-block:: python
if blah == 0:
def printarg (arg):
if name == "main":
Remove duplicates from a list
.. code-block:: python
the_list = list(set(the_list))
Profile a program
http://docs.python.org/library/profile.html
.. code-block:: python
import profile
profile.run("main()")
Launch REPL when line is hit
.. code-block:: python
import code
code.interact(local=locals())
Logging
.. code-block:: python
import logging
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.warning('%s before you %s', 'Look', 'leap!')
Named tuples (ghetto classes)
.. code-block:: python
import collections
Prisoner = collections.namedtuple('Prisoner', 'name rank serial')
hogan = Person(name='Hogan', age='Colonel', serial='1234')
lebeau = Person(name='Lebeau', age='Private', serial='8888')
print 'Name:', lebeau.name
for prisoner in [ hogan, lebeau ]:
Tab completion in Python shell
If you don't have access to IPython,
.. code-block:: python
import rlcompleter, readline
readline.parse_and_bind('tab: complete')
Tar a bunch of files
.. code-block:: python
import tarfile
tar = tarfile.open("sample.tar", "w")
for name in ["foo", "bar", "quux"]:
Run a simple webserver
::
python -m SimpleHTTPServer
Check Python version
.. code-block:: python
if sys.hexversion >= 0x020502F0:
...
...
bit | description |
---|---|
1-8 | PY_MAJOR_VERSION (the 2 in 2.1.0a3) |
9-16 | PY_MINOR_VERSION (the 1 in 2.1.0a3) |
17-24 | PY_MICRO_VERSION (the 0 in 2.1.0a3) |
25-28 | PY_RELEASE_LEVEL (0xA for alpha, 0xB for beta, 0xC for release candidate and 0xF for final) |
29-32 | PY_RELEASE_SERIAL (the 3 in 2.1.0a3, zero for final releases) |
Get Linux distribution
.. code-block:: python
if sys.hexversion < 0x020600F0:
Inspect the stack
.. code-block:: python
import inspect
print " << ".join([i[3] for i in inspect.stack()])
Get Python documentation through the browser
::
pydoc -p <port>