Python Notes

Python Tools

To start a local HTTP server:

python -m SimpleHTTPServer 8080  # Python 2
python -m http.server 8080       # Python 3

Dependency Management

To keep your Python environments nice and clean, use VirtualEnv.

Install

pip install --user virtualenv

Project Setup

In the project directory:

virtualenv ENV

This will create an ENV directory.

Usage

Whenever you want to do anything in your project, run:

source ENV/bin/activate

Now you can install things normally with pip, eg:

pip3 install torch torchvision

Once you’re done, run deactivate.

Distributing

To save the state of your environment, run:

pip freeze > requirements.txt

And then somebody else can run:

pip install -r requirements.txt

Docker

Docker packaging guide for Python

Web Server

Bottle is a decent web server to use.

from bottle import Bottle, route, run

app = Bottle()

@app.route('/')
def hello():
    # Query parameters like http://localhost:8080?name=John
    name = request.query.name or "Peter"
    return "Hello " + name

app.run(host='localhost', port=8080, debug=True)