Created
September 6, 2017 04:17
-
-
Save aconz2/7222a677a53de7ba098b8f5c35a62bc6 to your computer and use it in GitHub Desktop.
A program that launches a dmenu choice of index terms to open python docs; or lets you search for a term; works with multiple versions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3.6 | |
import re | |
from subprocess import run, PIPE | |
from pathlib import Path | |
import requests | |
import zipfile | |
import io | |
import pickle | |
import urllib | |
def searches(pattern, it): | |
for x in it: | |
match = re.search(pattern, x) | |
if match: | |
yield match.groups() | |
WORKING_DIR = Path('~/.pydocs').expanduser() | |
WORKING_DIR.mkdir(exist_ok=True) | |
dir_version = lambda version: WORKING_DIR.joinpath(f'python-{version}-docs-html') | |
url_version = lambda version, rest: 'file://{}/{}'.format(dir_version(version), rest) | |
def download_docs(version): | |
url = f'https://docs.python.org/ftp/python/doc/{version}/python-{version}-docs-html.zip' | |
r = requests.get(url) | |
with io.BytesIO(r.content) as bh: | |
with zipfile.ZipFile(bh) as zh: | |
zh.extractall(WORKING_DIR) | |
def ensure_docs(version): | |
if not dir_version(version).exists(): | |
download_docs(version) | |
def create_index(version): | |
with open(dir_version(version).joinpath('genindex-all.html')) as fh: | |
return {name: url for url, name in searches(r'<dt><a href="([^"]+)">(\w+)', fh)} | |
def ensure_index(version): | |
fp = dir_version(f'index-{version}.pkl') | |
if not fp.exists(): | |
index = create_index(version) | |
with open(fp, 'wb') as fh: | |
pickle.dump(index, fh) | |
return index | |
with open(fp, 'rb') as fh: | |
return pickle.load(fh) | |
def launch_chrome(url): | |
run(['google-chrome', f'--app={url}']) | |
def dmenu_choice(choices): | |
return run(['dmenu'], input='\n'.join(choices), universal_newlines=True, check=True, stdout=PIPE).stdout.strip() | |
def go(version): | |
ensure_docs(version) | |
index = ensure_index(version) | |
choice = dmenu_choice(index.keys()) | |
if choice in index: | |
launch_chrome(url_version(version, index[choice])) | |
def search(version): | |
ensure_docs(version) | |
term = urllib.parse.quote(dmenu_choice([])) | |
launch_chrome(url_version(version, f'search.html?q={term}')) | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--version', default='3.6.2') | |
parser.add_argument('--search', default=False, action='store_true') | |
args = parser.parse_args() | |
if args.search: | |
search(args.version) | |
else: | |
go(args.version) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment