Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:02
Show Gist options
  • Save paulsmith/c93be2cc3a303b86f4c4 to your computer and use it in GitHub Desktop.
Save paulsmith/c93be2cc3a303b86f4c4 to your computer and use it in GitHub Desktop.
start a file-serving web server in a directory on an OS-assigned port and opens browser to the root
# Copyright 2014 Paul Smith
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# See the License for the specific language governing permissions and
# limitations under the License.
# Starts a file-serving HTTP server on an OS-assigned port and opens the default
# web browser to the root URL (i.e., the directory it was started in).
# Uses `open(1)` which is OS X-only.
f1=/tmp/.$(basename $0).$$.1
f2=/tmp/.$(basename $0).$$.2
mkfifo $f1 $f2
trap "rm -f $f1 $f2" EXIT
grep --line-buffered -E '^Serving HTTP on .* port .* \.\.\.$' < $f1 | \
sed -l -E -e 's|Serving HTTP on (.+) port (.+) \.\.\.|http://\1:\2/|' > $f2 &
read addr <$f2
echo $addr
open $addr
} &
python -u -m SimpleHTTPServer 0 | tee $f1
Copy link

Everyone knows python -m SimpleHTTPServer to start a quick webserver in a directory, it's pretty awesome. It either mounts on port 8000 by default or you can give it an alternate port as an command line argument. But if you're like me, you have lots of server processes running at once, you often get conflicts where the port is already in use, or you have to hunt and peck for a free one.

It's much better to just let the OS assign an unused port to this quick webserver process, since you don't really care where it goes. You can do this by passing 0 as the port argument, and that totally works: Python prints out the port it started the HTTP server on. There's just one problem that trips me up: it prints out this new port number in such a way that you have to either mouse over, select, copy, open a new tab, paste, after typing in "localhost" or "", or you have to eyeball it and type it in with the new tab:

$ python -m SimpleHTTPServer 0
Serving HTTP on port 61200 ...

See what I mean, you have to snag that 61200 somehow. I just want to start a webserver and have it immediately open to that address in my browser! That output should be clickable or hook into OS X's open.

So this shell script does that.

$ ./webserver
Serving HTTP on port 61209 ... - - [19/Jun/2014 17:21:56] "GET / HTTP/1.1" 200 - - - [19/Jun/2014 17:21:57] code 404, message File not found - - [19/Jun/2014 17:21:57] "GET /favicon.ico HTTP/1.1" 404 -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment