File Under: Software & Tools

Answer Your Coding Questions Without Leaving the Command Line

Imagine you’re hard at work, writing some code in Vim or Emacs and you can’t remember some boilerplate bit of code, say, how to format a date. You’re in the terminal working and you don’t want to switch over to your browser window which has dozens of distractions clamoring for your attention, what do you do? Use howdoi.

The aptly named howdoi is a little command line client that queries Stack Overflow by doing a Google site search and scraping the results to return just the nugget of code you need.

For example, say you want to know how to format a date in the Jinja Template language. Just query howdoi:

howdoi format date jinja2
{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}

The response isn’t perfect, but it’s probably enough to remind you that Jinja2 just uses Python’s strftime function. If that’s not enough, howdoi has some optional flags that can help. Howdoi’s most useful flag is probably the -a flag, which return the entire Stack Overflow answer. In the case of our Jinja question here’s what the entire answer looks like:

howdoi format date jinja2 -a
There are two ways to do it. The direct approach would be to simply call (and print) the strftime() method in your template, for example {{ car.date_of_manufacture.strftime('%Y-%m-%d') }} Another, sightly better approach would be to define your own filter, e.g.: def format_datetime(value, format='medium'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format="EE dd.MM.y HH:mm"
    return babel.format_datetime(value, format)

jinja_env.filters['datetime'] = format_datetime (This filter is based on babel for reasons regarding i18n, but you can use strftime too). The advantage of the filter is, that you can write {{ car.date_of_manufacture|datetime }} which looks nicer and is more maintainable. Another common filter is also the "timedelta" filter, which evaluates to something like "written 8 minutes ago". You can use babel.format_timedelta for that, and register it as filter similar to the datetime example given here.

If you’d like to see more results, you can use the -p (position) flag to see whichever results you’d like. For example howdoi format date jinja2 -p2 would show the second result and so on.

As with site searches in a browser, howdoi’s results can be hit or miss — it really depends on the quality of answers on Stack Overflow, which is obviously somewhat narrower than just a Google search. Still if you’re the type that’s easily distracted or just really loves the command line, you’ll probably enjoy howdoi. You can grab the code from GitHub and be sure to check out the readme for a complete list of commands.