print a text by specifying the width via a variable

July 11, 2014 Leave a comment

Problem
You want to print a text using a certain width that you want to specify via a variable. Running example:

$ ./test.py 
Width: 10
'     World'
Width: 20
'               World'

Solution

for _ in range(2):
    width = int(raw_input("Width: "))
    print("'{0:>{w}}'".format("World", w=width))

The sign ‘>‘ can be omitted. It simply means “align to the right”.

Tip from here.

Categories: python Tags: ,

Django show_urls formatter

July 11, 2014 Leave a comment

Today I wrote a little script to beautify the output of the command “manage.py show_urls“. The script is available on GitHub here. For more info, visit the previous GitHub link.

Screenshots
Normal usage:

$ ./manage.py show_urls

before

Adding the beautifier:

$ ./manage.py show_urls | fmt.py

after

awesome Python

July 2, 2014 1 comment

awesome-python is a curated list of awesome Python frameworks, libraries and software. Inspired by awesome-php.

Have you ever wondered what kind of packages to use for geolocation for instance? Here you will find the answer.

The good thing is that the libraries are put in categories.

Categories: python

built-in Python modules you should know

June 24, 2014 Leave a comment

Here is an interesting thread about built-in modules that you should know: http://redd.it/28yo37 . If you wonder how to improve your Python knowledge, check ‘em out.

In the thread some useful 3rd party modules are also listed.

Categories: python Tags:

call a function by knowing its name as a string

June 24, 2014 Leave a comment

Problem
I want to call a function but its name is stored in a string. How to do that?

Solution
I wanted to create a menu where the user can select which entry to call. It looks like this:

(1)[r] radio
(2)[ctd] create temp. directory
--------
[m] menu
[q] <

In Python I stored it like this:

menu = OrderedDict()
menu[(1, 'r')] = ('radio', 'apps.radio.radio_player')
menu[(2, 'ctd')] = ('create temp. directory', 'apps.temp_folder.create_temp_folder')

That is, if the user selects “1“, then apps.radio.radio_player() must be called.

Here is the method that can call the appropriate function:

import importlib

def start_app(val):
    """
    Call a function by name (string).
    
    Tip from here: http://stackoverflow.com/questions/3061 .
    """ 
    _, to_call = val
    function_string = to_call # ex.: 'apps.radio.radio_player'
    mod_name, func_name = function_string.rsplit('.', 1)
    mod = importlib.import_module(mod_name)
    func = getattr(mod, func_name)
    func()

The tip is from here.

extract all links from a file

June 17, 2014 Leave a comment

Problem
You want to extract all links (URLs) from a text file.

Solution

def extract_urls(fname):
    with open(fname) as f:
        return re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', f.read())
Categories: python Tags: , ,

Is a file binary?

June 17, 2014 Leave a comment

Problem
I want to process all text files in a folder recursively. (Actually, I want to extract all URLs from them). However, their extensions are not necessarily .txt. How to separate text files from binary files?

Solution
In this thread I found a solution. Here is my slightly modified version:

def is_binary(fname):
    """
    Return true if the given filename is binary.

    found at http://stackoverflow.com/questions/898669
    """
    CHUNKSIZE = 1024
    with open(fname, 'rb') as f:
        while True:
            chunk = f.read(CHUNKSIZE)
            if '\0' in chunk: # found null byte
                return True
            if len(chunk) < CHUNKSIZE:
                break # done

    return False

If it finds a '\0' character, then the file is considered to be binary. Note that it will also classify UTF-16-encoded text files as “binary”.

Categories: python Tags: ,
Follow

Get every new post delivered to your Inbox.

Join 65 other followers