#! /usr/bin/env python from cgi import parse_qsl from getopt import getopt, GetoptError import sys, urllib from m_lib.defenc import default_encoding # This must be imported and called before webbrowser # because webbrowser reads BROWSER environment variable at the import time from browser_stack import set_current_browser set_current_browser() import webbrowser def usage(): sys.exit('Usage: %s [-e|--encoding=encoding] [-n|--newwin|-t|--tab] URL' % sys.argv[0]) try: options, arguments = getopt(sys.argv[1:], 'e:nt', ['encoding=', 'newwin', 'tab']) except GetoptError: usage() if len(arguments) <> 1: usage() encoding = None new = 0 for option, value in options: if option in ('-e', '--encoding'): encoding = value elif option in ('-n', '--newwin'): new = 1 elif option in ('-t', '--tab'): new = 2 if not encoding: encoding = default_encoding url = arguments[0] protocol, request = urllib.splittype(url) user, password, port = None, None, None host, path = urllib.splithost(request) if host: user, host = urllib.splituser(host) if user: user, password = urllib.splitpasswd(user) host, port = urllib.splitport(host) if port: port = int(port) path, tag = urllib.splittag(path) path, query = urllib.splitquery(path) path = urllib.unquote(path) if tag: tag = urllib.unquote_plus(tag) if query: qlist = [] for name, value in parse_qsl(query): name = unicode(name, default_encoding).encode(encoding) value = unicode(value, default_encoding).encode(encoding) qlist.append((name, value)) url = protocol + "://" if user: url += urllib.quote(unicode(user, default_encoding).encode(encoding)) if password: url += ':' + urllib.quote(unicode(password, default_encoding).encode(encoding)) url += '@' if host: url += host.decode(encoding).encode('idna') if port: url += ':%d' % port if path: if protocol == "file": url += urllib.quote(path) else: url += urllib.quote(unicode(path, default_encoding).encode(encoding)) if query: url += '?' + urllib.urlencode(qlist) if tag: url += '#' + urllib.quote_plus(unicode(tag, default_encoding).encode(encoding)) webbrowser.open(url, new)