title: Convert a filename to a file:// URL
body: <p>In WeasyPrint’s public API I accept filenames (among other types) for the HTML inputs. Any filename that works with the built-in <code>open()</code> should work, but I need to convert it to an URL in the <code>file://</code> scheme that will later be passed to <code>urllib.urlopen()</code>.</p>
  <p>(Everything is in URL form internally. I need to have a &quot;base URL&quot; for documents in order to resolve relative URL references with <code>urlparse.urljoin()</code>.)</p>
  <p><a href="http://docs.python.org/library/urllib.html#urllib.pathname2url" rel="nofollow noreferrer">urllib.pathname2url</a> is a start:</p>
  <blockquote>
  <p>Convert the pathname path from the local syntax for a path to the form used in the path component of a URL. <strong>This does not produce a complete URL.</strong> The return value will already be quoted using the quote() function.</p>
  </blockquote>
  <p>The emphasis is mine, but I do need a complete URL. So far this seems to work:</p>
  
  <pre class="lang-py prettyprint-override"><code>def path2url(path):
      &quot;&quot;&quot;Return file:// URL from a filename.&quot;&quot;&quot;
      path = os.path.abspath(path)
      if isinstance(path, unicode):
          path = path.encode('utf8')
      return 'file:' + urlparse.pathname2url(path)
  </code></pre>
  <p>UTF-8 seems to be recommended by <a href="https://www.rfc-editor.org/rfc/rfc3987" rel="nofollow noreferrer">RFC 3987 (IRI)</a>. But in this case (the URL is meant for urllib, eventually) maybe I should use <a href="http://docs.python.org/library/sys.html#sys.getfilesystemencoding" rel="nofollow noreferrer">sys.getfilesystemencoding()</a>?</p>
  <p>However, based on <a href="https://en.wikipedia.org/wiki/File_URI_scheme" rel="nofollow noreferrer">the literature</a> I should prepend not just <code>file:</code> but <code>file://</code> ... except when I should not: On Windows the results from <code>nturl2path.pathname2url()</code> already start with three slashes.</p>
  <p>So the question is: is there a better way to do this and make it cross-platform?</p>