Rebased on origin/master to resolve a context conflict due to the
Python 3 `except OSError as e` change.