Archive

Archive for February, 2013

Python’s Magic Methods

February 28, 2013 Leave a comment

see Rafe Kettler’s “A Guide to Python’s Magic Methods

What are magic methods? They’re everything in object-oriented Python. They’re special methods that you can define to add “magic” to your classes. They’re always surrounded by double underscores (e.g. __init__ or __lt__). They’re also not as well documented as they need to be. All of the magic methods for Python appear in the same section in the Python docs, but they’re scattered about and only loosely organized. There’s hardly an example to be found in that section (and that may very well be by design, since they’re all detailed in the language reference, along with boring syntax descriptions, etc.).

Advertisements
Categories: python Tags: , ,

Using Jinja2 for formatting strings

February 27, 2013 3 comments

Example 1

from jinja2 import Environment

config = {
    'ffmpeg': '/opt/ffmpeg.static/ffmpeg',
    'bitrate': '600k',
    'width': '480',
    'height': '320',
    'threads': '2'
}

command = """{{ ffmpeg }} -i {input} -codec:v libx264 -quality good -cpu-used 0
-b:v {{ bitrate }} -profile:v baseline -level 30 -y -maxrate 2000k
-bufsize 2000k -vf scale={{ width }}:{{ height }} -threads {{ threads }} -codec:a libvo_aacenc
-b:a 128k {output}""".replace('\n', ' ')

command = Environment().from_string(command).render(config)

print command

Output:

/opt/ffmpeg.static/ffmpeg -i {input} -codec:v libx264 -quality good -cpu-used 0 -b:v 600k -profile:v baseline -level 30 -y -maxrate 2000k -bufsize 2000k -vf scale=480:320 -threads 2 -codec:a libvo_aacenc -b:a 128k {output}

Here, command is still a template that can be further formatted, e.g.

print command.format(input="movie.avi", output="movie.mp4")

Example 2

Now let’s see a simpler example:

from jinja2 import Environment

print Environment().from_string("Hello {{ name }}!").render(name="Laci")

Output: “Hello Laci!”.

More examples
See https://gist.github.com/warren-runk/1317933.

Update (20130301)
Here I show you how to avoid using jinja2 :) Let’s take the first example above where jinja2 formatting was combined with Python’s string formatting.

Actually, in this example, jinja2 may be an overkill. We can combine old-style formatting and new-style formatting to have the same result:

config = {
    'ffmpeg': '/opt/ffmpeg.static/ffmpeg',
    'bitrate': '600k',
    'width': '480',
    'height': '320',
    'threads': '2'
}

command = """{ffmpeg} -i %(input)s -codec:v libx264 -quality good -cpu-used 0
-b:v {bitrate} -profile:v baseline -level 30 -y -maxrate 2000k
-bufsize 2000k -vf scale={width}:{height} -threads {threads} -codec:a libvo_aacenc
-b:a 128k %(output)s""".replace('\n', ' ').format(**config)

Now we have a template that can be further formatted in a loop for instance:

print command % {'input': fname, 'output': output}

Thanks bulkan for the tip.