Fork me on GitHub
  1. Python UTF-8 print fails when redirecting stdout

    Consider the following piece of code:

    # -*- coding: utf-8 -*-
    print u"Վարդանաշեն"
    

    Running this in a terminal works:

    $ python test.py
    Վարդանաշեն
    

    Redirecting standard output to a file fails:

    $ python test.py > file
    Traceback (most recent call last):
      File "test.py", line 2, in <module>
        print u"Վարդանաշեն"
    UnicodeEncodeError: 'ascii' codec …
    read more

    There are comments.

  2. Python lazy hasattr()

    Python hasattr() evaluates the specified attribute, which may not be desired !

    class Attr(object):
        def __get__(self, obs, cls=None):
            print "evaluated"
            return 0
    
    class ClassA(object):
        a = Attr()
    
        @property
        def b(self):
            print "evaluated"
            return 0
    
    >>> c = ClassA()
    >>> c.a
    evaluated
    0
    >>> c.b
    evaluated
    0
    

    Now note that …

    read more

    There are comments.

  3. Filesystem Watch with PyQt4

    I decided to write a generic program that can watch a folder or some files and run a command when changes occur.

    Most of the work is done by PyQt4's QFileSystemWatcher.

    qfsw = QtCore.QFileSystemWatcher()
    qfsw.addPaths([path1, file2 ... ])
    
    QtCore.QObject.connect(qfsw,QtCore.SIGNAL("directoryChanged(QString)"),function)
    QtCore.QObject.connect …
    read more

    There are comments.

  4. Text extents with Python Cairo

    I needed this and could not find it. So I share it here (and even better if Google'd index it!)

    def textwidth(text, fontsize=14):
        try:
            import cairo
        except Exception, e:
            return len(str) * fontsize
        surface = cairo.SVGSurface('undefined.svg', 1280, 200)
        cr = cairo.Context(surface)
        cr.select_font_face('Arial', cairo …
    read more

    There are comments.

  5. Colored Output in Console with Python

    Playing around with ANSI in a color capable terminal.

    #!/usr/bin/env python
    import sys
    
    BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
    
    #following from Python cookbook, #475186
    def has_colours(stream):
        if not hasattr(stream, "isatty"):
            return False
        if not stream.isatty():
            return False # auto color only on …
    read more

    There are comments.

« Page 3 / 3

social