1 #! /usr/bin/env python3
4 from urllib.parse import parse_qsl, urlencode, \
5 quote, quote_plus, unquote, unquote_plus, \
6 splittype, splithost, splituser, splitpasswd, \
7 splitport, splittag, splitquery
9 from cgi import parse_qsl
10 from urllib import urlencode, quote, quote_plus, unquote, unquote_plus, \
11 splittype, splithost, splituser, splitpasswd, \
12 splitport, splittag, splitquery
13 from getopt import getopt, GetoptError
15 from m_lib.defenc import default_encoding
17 # This must be imported and called before webbrowser
18 # because webbrowser reads BROWSER environment variable at the import time
19 from browser_stack import set_current_browser
25 sys.exit('Usage: %s [-e|--encoding=encoding] [-n|--newwin|-t|--tab] URL' % sys.argv[0])
28 options, arguments = getopt(sys.argv[1:], 'e:nt', ['encoding=', 'newwin', 'tab'])
32 if len(arguments) != 1:
38 for option, value in options:
39 if option in ('-e', '--encoding'):
41 elif option in ('-n', '--newwin'):
43 elif option in ('-t', '--tab'):
47 encoding = default_encoding
50 protocol, request = splittype(url)
51 user, password, port = None, None, None
52 host, path = splithost(request)
54 user, host = splituser(host)
56 user, password = splitpasswd(user)
57 host, port = splitport(host)
58 if port: port = int(port)
59 path, tag = splittag(path)
60 path, query = splitquery(path)
62 if tag: tag = unquote_plus(tag)
66 for name, value in parse_qsl(query):
67 if isinstance(name, bytes):
68 name = name.decode(default_encoding)
69 value = value.decode(default_encoding)
70 name = name.encode(encoding)
71 value = value.encode(encoding)
72 qlist.append((name, value))
74 url = protocol + "://"
76 if isinstance(user, bytes):
77 user = user.decode(default_encoding)
78 url += quote(user.encode(encoding))
80 if isinstance(password, bytes):
81 password = password.decode(default_encoding)
82 url += ':' + quote(password.encode(encoding))
85 if isinstance(host, bytes):
86 host = host.decode(encoding)
87 url += host.encode('idna').decode('ascii')
91 if protocol == "file":
94 if isinstance(path, bytes):
95 path = path.decode(default_encoding)
96 url += quote(path.encode(encoding))
98 url += '?' + urlencode(qlist)
100 if isinstance(tag, bytes):
101 tag = tag.decode(default_encoding)
102 url += '#' + quote_plus(tag.encode(encoding))
104 webbrowser.open(url, new)