nturl2path.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """Convert a NT pathname to a file URL and vice versa."""
  2. def url2pathname(url):
  3. """OS-specific conversion from a relative URL of the 'file' scheme
  4. to a file system path; not recommended for general use."""
  5. # e.g.
  6. # ///C|/foo/bar/spam.foo
  7. # and
  8. # ///C:/foo/bar/spam.foo
  9. # become
  10. # C:\foo\bar\spam.foo
  11. import string, urllib
  12. # Windows itself uses ":" even in URLs.
  13. url = url.replace(':', '|')
  14. if not '|' in url:
  15. # No drive specifier, just convert slashes
  16. if url[:4] == '////':
  17. # path is something like ////host/path/on/remote/host
  18. # convert this to \\host\path\on\remote\host
  19. # (notice halving of slashes at the start of the path)
  20. url = url[2:]
  21. components = url.split('/')
  22. # make sure not to convert quoted slashes :-)
  23. return urllib.unquote('\\'.join(components))
  24. comp = url.split('|')
  25. if len(comp) != 2 or comp[0][-1] not in string.ascii_letters:
  26. error = 'Bad URL: ' + url
  27. raise IOError, error
  28. drive = comp[0][-1].upper()
  29. path = drive + ':'
  30. components = comp[1].split('/')
  31. for comp in components:
  32. if comp:
  33. path = path + '\\' + urllib.unquote(comp)
  34. # Issue #11474: url like '/C|/' should convert into 'C:\\'
  35. if path.endswith(':') and url.endswith('/'):
  36. path += '\\'
  37. return path
  38. def pathname2url(p):
  39. """OS-specific conversion from a file system path to a relative URL
  40. of the 'file' scheme; not recommended for general use."""
  41. # e.g.
  42. # C:\foo\bar\spam.foo
  43. # becomes
  44. # ///C:/foo/bar/spam.foo
  45. import urllib
  46. if not ':' in p:
  47. # No drive specifier, just convert slashes and quote the name
  48. if p[:2] == '\\\\':
  49. # path is something like \\host\path\on\remote\host
  50. # convert this to ////host/path/on/remote/host
  51. # (notice doubling of slashes at the start of the path)
  52. p = '\\\\' + p
  53. components = p.split('\\')
  54. return urllib.quote('/'.join(components))
  55. comp = p.split(':')
  56. if len(comp) != 2 or len(comp[0]) > 1:
  57. error = 'Bad path: ' + p
  58. raise IOError, error
  59. drive = urllib.quote(comp[0].upper())
  60. components = comp[1].split('\\')
  61. path = '///' + drive + ':'
  62. for comp in components:
  63. if comp:
  64. path = path + '/' + urllib.quote(comp)
  65. return path