Python snippets #1

Simple HTTP server to provide web access to directory

Use:

# Python3:
python3 -m http.server
 
# Python2:
python -m SimpleHTTPServer

Now visit http://<your-ip-address>:8000/ to browse the directory where you launched the command. Includes directory index and file/dir navigation.

Also


Send a file through the network with Zerozonf

Send a file that can be directly get from the network with zget (pypi.python.org).

# Sender:
$ zput filename
 
# Receiver:
$ zget filename


Sort strings that contain numbers correctly (IPs, paths..)

def natural_sort(item):
    """
    Sort strings that contain numbers correctly.
 
    >>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
    >>> l.sort(key=natural_sort)
    >>> print l
    "['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
    """
    if item is None: return 0
    def try_int(s):
        try: return int(s)
        except ValueError: return s
    return map(try_int, re.findall(r'(\d+|\D+)', item))

If you want to sort paths (*nix and/or Windows) using this technique, then you might want to modify the regex to also split on path separators:

return map(try_int, re.findall(r'(\d+|\D+|[/\\])', item))


Inject a timestamp into a filename

import datetime
import os.path
def time_stamp(filename, fmt='%Y_%m_%d_%H_%M_%S'):
    ''' injects a timestamp into a file name '''
    name, ext = os.path.splitext(filename)
    now = datetime.datetime.now()
    return '{name}__{now:{fmt}}{ext}'.format(**vars())


List flattening

nest = [[1, 2], [3, 4], [5, 6]]
 
## Using chain
>>> from itertools import chain
>>> list(chain.from_iterable(nest))
[1, 2, 3, 4, 5, 6]
 
## Using sum
>>> sum(nest, [])
[1, 2, 3, 4, 5, 6]
 
## Using List Comprehensions
>>> [l for n in nest for l in n]
[1, 2, 3, 4, 5, 6]


def print_thread_stacks(logger):
    import traceback,sys
    logger.warn("\n*** STACKTRACE - START ***\n")
    code = []
    for threadId, stack in sys._current_frames().items():
        code.append("\n# ThreadID: %s" % threadId)
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line: code.append("  %s" % (line.strip()))
    for line in code: logger.warn(line)
    logger.warn("\n*** STACKTRACE - END ***\n")


Convert an epoch time to a datetime object

def epoch_to_dt(epoch):
    '''Convert an epoch time to a datetime object'''
    return datetime(*gmtime(epoch)[:6])


Pretty NOW()

def pretty_now():
    """Returns some thing like '2014-07-24 11:12:45 CEST+0200'"""
    now = datetime.datetime.now(dateutil.tz.tzlocal())
    return now.strftime("%Y-%m-%d %H:%M:%S %Z%z")


UNIX's head and tail implemented in python

def tail(path, window=20):
    with open(path, 'r') as f:
        BUFSIZ = 1024
        f.seek(0, 2)
        num_bytes = f.tell()
        size = window + 1
        block = -1
        data = []
        while size > 0 and num_bytes > 0:
            if num_bytes - BUFSIZ > 0:
                # Seek back one whole BUFSIZ
                f.seek(block * BUFSIZ, 2)
                # Read BUFFER
                data.insert(0, f.read(BUFSIZ))
            else:
                # File too small, start from beginning
                f.seek(0,0)
                # Only read what was not read
                data.insert(0, f.read(num_bytes))
            linesFound = data[0].count('\n')
            size -= linesFound
            num_bytes -= BUFSIZ
            block -= 1
        return '\n'.join(''.join(data).splitlines()[-window:])
 
def head(path, lines=20):
    with open(path, 'r') as handle:
        return ''.join(handle.next() for line in xrange(lines))


Python-scripts snippets repository

$ git clone https://github.com/realpython/python-scripts



<Volver a la sección de Tutoriales Python>