#!/usr/bin/env python """ Translates URLs based on a format string. All occurrences of ``'%' letter`` patterns in format are tried to be substituted with a component from the given URL. Following patterns are supported: * ``'%s'``: Scheme * ``'%l'``: Network location * ``'%p'``: Path * ``'%q'``: Query * ``'%f'``: Fragment * ``'%u'``: Username * ``'%w'``: Password * ``'%h'``: Hostname * ``'%o'``: Port * ``'%%'``: Literal ``'%'`` To use see url.rewrite() or CLI utility. """ import argparse import re from urllib.parse import urlsplit def rewrite(url, fmt): "Translates *url* to *fmt*." url = urlsplit(url) mapping = { "s": url.scheme, "l": url.netloc, "p": url.path, "q": url.query, "f": url.fragment, "u": url.username or "", "w": url.password or "", "h": url.hostname or "", "o": url.port or "", "%": "%", } regex = re.compile(f"%([{''.join(mapping.keys())}])") def _replace(match): return mapping[match.group(1)] return regex.sub(_replace, fmt) def main(): "Translates URL to FMT." parser = argparse.ArgumentParser(description=main.__doc__) parser.add_argument("FMT") parser.add_argument("URL") args = parser.parse_args() print(rewrite(args.URL, args.FMT)) if __name__ == "__main__": main()