Python

Must-read

Packages

Packaging

Dev environment

  • Package management. Python lacks package management tool comparable with Perl CPAN or Ruby Gems, though pip and easy_install make it easier (more discussion).
  • Python IDEs. Here is a discussion at stack overflow.
  • Virtual environment – virtualenv and virtualenvwrapper

How-tos

  • Calculate entropy (here)
  • Flat a list of lists (here). [item for sublist in l for item in sublist]
  • Capture the output when running system commands. (here)

    For convenience, Python 2.7 provides the

    subprocess.check_output(*popenargs, **kwargs)  

    function, which takes the same arguments as Popen, but returns a string containing the program’s output. You’ll still want to pass stderr=subprocess.STDOUT because that will ensure that error messages are included in the returned output. See here for documentation.

    Also, although Vartec’s method will work, the better way to go if you’re using an older Python — at least in simple cases that don’t require real-time output capturing — would be to use communicate. As in:

    output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

    Or

    >>> import subprocess
    >>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, 
                                           stderr=subprocess.PIPE)
    >>> out, err = p.communicate()
    >>> print out
    .
    ..
    foo
  • Fill out a string with spaces: str.ljust(width[, fillchar])
  • How to find the location of Python modules: foo.__file__ (more)
  • Union keys from multiple dicts (here)
  • allkey = reduce(lambda x, y: x.union(y.keys()), alldict, set())

    An alternative without any lambdas would be:

    allkey = reduce(set.union, map(set, map(dict.keys, alldict)))
  • Sorting, sort a dictionary by value
  • Declare function at the end of file
  • Print to STDERR: sys.stderr.write()
  • PyDev 3.0 does not work under OSX. Follow the user3056710‘s solution at here.
  • Install package without root access? See here.
  • Know if an object has an attribute in Python?
    if hasattr(a, 'property'):
        a.property

    Or, you really just want the value of the attribute with a default if it isn’t there, the best option is

    getattr(a, 'property', 'default value')

    More.

  • Rename a dictionary key. More about pop.
    mydict[new_key] = mydict.pop(old_key)
  • List comprehension examples (here).
    [(x, y, x * y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]
    total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if x < y)
  • csv DictReader and DictWriter example (here)
Advertisements