Archive

Posts Tagged ‘string formatting’

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.