#!/bin/python3 from contextlib import contextmanager import colorama import time import datetime import dateutil.tz import bs4 import urllib.parse @contextmanager def init_colorama(): """Set global foreground modifying ANSI codes. BLACK, BLUE, CYAN, GREEN, MAGENTA, RED, WHITE, YELLOW, and RESET. """ # pylint: disable=exec-used,invalid-name colorama.init() for color, ansi in colorama.Fore.__dict__.items(): exec("global {0}; {0} = '{1}'".format(color, ansi)) yield for color in colorama.Fore.__dict__: exec("global {0}; {0} = ''".format(color)) colorama.deinit() def current_datetime(): """Return the current datetime, complete with tzinfo. Precision is one second. Timezone is the local timezone. """ return datetime.datetime.fromtimestamp(round(time.time()), dateutil.tz.tzlocal()) def absolutify_links(soup, baseurl): """Make links in an article absolute. Parameters ---------- soup : bs4.BeautifulSoup baseurl : str """ for tag in soup.find_all(lambda tag: tag.has_attr("href")): tag["href"] = urllib.parse.urljoin(baseurl, tag["href"]) for tag in soup.find_all(lambda tag: tag.has_attr("src")): tag["src"] = urllib.parse.urljoin(baseurl, tag["src"])