cat /dev/brain

One-liners

I'm just going to collect some useful one-liners that I've either made myself or found elsewhere. I think some of these might benefit some people I know, so there may be follow up posts to add more.

What's my IP? (python)

This requires requests but it could probably be done with a lot more work using urllib(2).

python -c "from requests import get; r = get('http://httpbin.org/ip');
print r.json['origin']"

#------------
# 24.0.10.20  (Not my real IP address)

What's my (network) IP? (bash+awk)

awk '/inet addr/ {print substr($2, 6, 20);}' <(ifconfig eth0)

#------------
# addr:192.168.254.254
# I used 20 just to be safe, this won't work for IPv6 addresses though

A simple HTTP server

screen -dmS pyserv python -m SimpleHTTPServer 8000

Obviously this expects that you have screen installed (I would guess that tmux has similar flags to name and background a session). Naturally, you may want to use this more than once, so you can turn it into a simple script or bash function (whichever you would prefer)

#!/bin/bash

if [[ -n $1 ]] ; then
    port="$1"
else
    port="8000"
fi

screen -dmS pyserv${port} python -m SimpleHTTPServer ${port}
echo "http://localhost:${port}"
echo "screen -r pyserv${port}"

Or if you'd rather just place a function into your .bashrc or .bash_profile (or wherever really)

pyserv() {
    if [[ -n $1 ]] ; then
        port="$1"
    else
        port="8000"
    fi

    screen -dmS pyserv${port} python -m SimpleHTTPServer ${port}
    echo "http://localhost:${port}"
    echo "screen -r pyserv${port}"
}

They should work the same, although I believe the latter will not fork a new shell before executing so it might be faster.

These also give you the URL to visit in your browser and give you the commands to resume the screen session so you can view the requests, errors, and kill the server. I mainly use this when I write these blog posts.

One final variation on this wonderful command is the ability to provide a directory to launch the server from:

pyserv() {
    if [[ -n $1 ]] ; then
        port="$1"
    else
        port="8000"
    fi

    old_dir="$(pwd)"

    if [[ -n $2 ]] ; then
        cd $2
    fi

    screen -dmS pyserv${port} python -m SimpleHTTPServer ${port}
    echo "http://localhost:${port}"
    echo "screen -r pyserv${port}"

    if ! [[ "$(pwd)" == $old_dir ]] ; then
        cd $old_dir
    fi
}

So if you use Sphinx to generate a website or some docs you can do:

~/project_dir$ make html
# ...
Build finished. The HTML pages are in _build/html.
~/project_dir$ pyserv 8000 _build/html