def _try_setcwd(path):
    """Try to set CWD to path, walking up until a valid directory is found.

    If no valid directory is found, a temp directory is created and cwd is set to that.
    """
    while path != '/':
        try:
            os.chdir(path)
        except OSError as e:
            exc = e  # break exception instance out of except scope
            print(f"Couldn't set CWD to {path} ({e})", file=sys.stderr)
            path, _ = os.path.split(path)
        else:
            return
    print(f"Couldn't set CWD at all ({exc}), using temp dir", file=sys.stderr)
    td = mkdtemp()
    os.chdir(td)
Try to set CWD to path, walking up until a valid directory is found.

If no valid directory is found, a temp directory is created and cwd is set to that.
jupyterhub/spawner.py