+def expanduser(path):
+ # os.path.expanduser is hopelessly broken for Unicode paths on Windows (ticket #1674).
+ if sys.platform == "win32":
+ return windows_expanduser(path)
+ else:
+ return os.path.expanduser(path)
+
+def windows_expanduser(path):
+ if not path.startswith('~'):
+ return path
+ home_drive = windows_getenv(u'HOMEDRIVE')
+ home_path = windows_getenv(u'HOMEPATH')
+ if path == '~':
+ return os.path.join(home_drive, home_path)
+ elif path.startswith('~/') or path.startswith('~\\'):
+ return os.path.join(home_drive, home_path, path[2 :])
+ else:
+ return path
+
+def windows_getenv(name):
+ # Based on <http://stackoverflow.com/questions/2608200/problems-with-umlauts-in-python-appdata-environvent-variable/2608368#2608368>,
+ # with improved error handling.
+ if not isinstance(name, unicode):
+ raise AssertionError("name must be Unicode")
+
+ n = GetEnvironmentVariableW(name, None, 0)
+ if n <= 0:
+ err = GetLastError()
+ raise OSError("Windows error %d attempting to read environment variable %r"
+ % (err, name))
+
+ buf = create_unicode_buffer(u'\0'*n)
+ retval = GetEnvironmentVariableW(name, buf, n)
+ if retval <= 0:
+ err = GetLastError()
+ raise OSError("Windows error %d attempting to read environment variable %r"
+ % (err, name))
+
+ return buf.value
+