Archive

Archive for the ‘python’ Category

Python Central

March 13, 2013 3 comments

pythoncentral-logoI found this site yesterday: http://pythoncentral.org/.

According to the FAQ, Python Central “…serves as a central place for Python enthusiasts, for anything and everything to do with the Python programming language. The content on the site is a combination of documentation of the library, a guide to learning the language, tips and tricks, and recipes.

Categories: python Tags:

PHP or Python?

March 8, 2013 Leave a comment
Categories: python Tags: , ,

docopt: a pythonic command line arguments parser that kicks your ass

March 7, 2013 Leave a comment

Docopt is a parser for command line arguments. There are other alternatives like optparse and argparse but docopt is the king. Why? Because it cannot be any simpler :) All you have to do is write an interface description to your script that is well-known from man pages and from the help of other command line applications.

Example (taken from the docopt site):

Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate.py -h | --help
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

Then you simply pass this string to docopt. When you execute the script, the parameters will be parsed by docopt according to the textual description above. Say you launch this script with the following parameters:

./naval_fate.py ship Guardian move 10 50 --speed=20

Docopt will parse it and return the following dictionary:

{"--drifting": false,
 "--help": false,
 "--moored": false,
 "--speed": "20",
 "--version": false,
 "<name>": ["Guardian"],
 "<x>": "10",
 "<y>": "50",
 "mine": false,
 "move": true,
 "new": false,
 "remove": false,
 "set": false,
 "ship": true,
 "shoot": false}

That’s all. You can try docopt online here.

If you got interested, watch the presentation of its author (you will find it on the top of the home page of the project).

It’s available on GitHub, where you can also check out some more examples.

Usage: either install it via pip, or just simply add the file docopt.py next to your script.

Getting started with Python: Tips, Tools and Resources

March 6, 2013 Leave a comment
Categories: python

Problem Solving with Algorithms and Data Structures Using Python

March 6, 2013 Leave a comment

Good news everyone. The book Problem Solving with Algorithms and Data Structures Using Python is available online in HTML format. This is the 2nd edition that came out in 2011.

amazon link

Categories: book, python Tags: ,

Execute command, show its output, get its exit code

March 3, 2013 Leave a comment

Problem
You want to execute an external program, show its output, and get its exit code at the end.

Solution

import shlex
from subprocess import Popen, PIPE

cmd = "..."
process = Popen(shlex.split(cmd), stdout=PIPE)
process.communicate()    # execute it, the output goes to the stdout
exit_code = process.wait()    # when finished, get the exit code

Example: I used this code with FFmpeg. FFmpeg updates the output on the stdout regularly while doing a conversion. At the end I can ask if the conversion was successful (exit_code == 0) or not.

Categories: python Tags: , ,

URL manipulation

March 1, 2013 1 comment

See the project furl. The API is here.

Python’s standard urllib and urlparse modules provide a number of URL manipulation functions, but using these functions to perform common URL manipulations proves tedious. Furl makes manipulating URLs simple.

Categories: python Tags: ,

Create an array of size N and initialize its values

March 1, 2013 Leave a comment

Problem
Create an array of size 10 and initialize all values to 0.

Solution
So far, I’ve done it like this (and I was proud of myself :))

li = [0 for _ in range(10)]

But the Pythonic way is this:

li = [0] * 10

Ehh :) Actually this creates 10 identical “[0]” lists and concatenates them. Lists can be concatenated by the way:

>>> [1,2] + [3,4]
[1, 2, 3, 4]

See this reddit post for more tips.

Categories: python Tags: ,

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.).

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.

Design a site like this with WordPress.com
Get started