1 #! /usr/bin/env python3
3 from getopt import getopt, GetoptError
4 from urllib.parse import urlsplit, parse_qsl, quote, quote_plus, urlencode
7 from m_lib.defenc import default_encoding
9 # This must be imported and called before webbrowser
10 # because webbrowser reads BROWSER environment variable at the import time
11 from browser_stack import set_current_browser
14 import webbrowser # noqa: E402 module level import not at top of file
18 sys.exit('Usage: %s [-e|--encoding=encoding] [-n|--newwin|-t|--tab] URL'
23 options, arguments = getopt(
24 sys.argv[1:], 'e:nt', ['encoding=', 'newwin', 'tab'])
28 if len(arguments) != 1:
34 for option, value in options:
35 if option in ('-e', '--encoding'):
37 elif option in ('-n', '--newwin'):
39 elif option in ('-t', '--tab'):
43 encoding = default_encoding
47 split_results = urlsplit(url)
48 protocol, netloc, path, query, tag = split_results
49 user = split_results.username
50 password = split_results.password
51 host = split_results.hostname
52 port = split_results.port
56 for name, value in parse_qsl(query):
57 if isinstance(name, bytes):
58 name = name.decode(default_encoding)
59 value = value.decode(default_encoding)
60 name = name.encode(encoding)
61 value = value.encode(encoding)
62 qlist.append((name, value))
64 url = protocol + "://"
66 if isinstance(user, bytes):
67 user = user.decode(default_encoding)
68 url += quote(user.encode(encoding))
70 if isinstance(password, bytes):
71 password = password.decode(default_encoding)
72 url += ':' + quote(password.encode(encoding))
75 if isinstance(host, bytes):
76 host = host.decode(encoding)
77 url += host.encode('idna').decode('ascii')
81 if protocol == "file":
84 if isinstance(path, bytes):
85 path = path.decode(default_encoding)
86 url += quote(path.encode(encoding))
88 url += '?' + urlencode(qlist)
90 if isinstance(tag, bytes):
91 tag = tag.decode(default_encoding)
92 url += '#' + quote_plus(tag.encode(encoding))
94 webbrowser.open(url, new)