#! /usr/bin/env python try: from urllib.parse import parse_qsl, urlencode, \ quote, unquote, unquote_plus, \ splittype, splithost, splituser, splitpasswd, \ splitport, splittag, splitquery except ImportError: from cgi import parse_qsl from urllib import urlencode, quote, unquote, unquote_plus, \ splittype, splithost, splituser, splitpasswd, \ splitport, splittag, splitquery from getopt import getopt, GetoptError import sys 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 = splittype(url) user, password, port = None, None, None host, path = splithost(request) if host: user, host = splituser(host) if user: user, password = splitpasswd(user) host, port = splitport(host) if port: port = int(port) path, tag = splittag(path) path, query = splitquery(path) path = unquote(path) if tag: tag = 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 += quote(unicode(user, default_encoding).encode(encoding)) if password: url += ':' + 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 += quote(path) else: url += quote(unicode(path, default_encoding).encode(encoding)) if query: url += '?' + urlencode(qlist) if tag: url += '#' + quote_plus(unicode(tag, default_encoding).encode(encoding)) webbrowser.open(url, new)