def render_file(tmplpath, tmpldict, bail_miss=False): """Renders the template file and the given path using the given template variable dictionary. Returns the rendered text as a string.""" tmplpath = op.abspath(tmplpath) env = Environment(undefined=SkipUndefined, extensions=['jinja2_time.TimeExtension']) env.trim_blocks = True env.lstrip_blocks = True env.keep_trailing_newline = True for encoding in ["utf-8", "mbcs"]: try: env.loader = FileSystemLoader(op.dirname(tmplpath), encoding=encoding) tmpl = env.get_template(op.basename(tmplpath)) break except UnicodeDecodeError: qprompt.warn("Issue while decoding template with `%s`!" % encoding) else: qprompt.fatal("Unknown issue while loading template!") with io.open(tmplpath) as fo: tmplstr = fo.read() miss = check_template(tmplstr, tmpldict) if miss: qprompt.warn("Template vars `%s` in `%s` were not supplied values!" % ("/".join(miss), op.basename(tmplpath))) return tmpl.render(**tmpldict)
def stop(): global TESTSERVER if not is_running(): warn("Application not running!") return TESTSERVER.stop() TESTSERVER = None alert("Application stopped.")
def stop(): global PROCS if not is_running(): warn("Application not running!") return for p in PROCS: p.stop() PROCS = [] alert("Application stopped.")
def render_str(tmplstr, tmpldict, bail_miss=False): """Renders the given template string using the given template variable dictionary. Returns the rendered text as a string.""" env = Environment(undefined=SkipUndefined, extensions=['jinja2_time.TimeExtension']) env.trim_blocks = True env.lstrip_blocks = True miss = check_template(tmplstr, tmpldict) if miss: qprompt.warn("Template vars `%s` were not supplied values!" % ("/".join(miss))) return env.from_string(tmplstr).render(**tmpldict)
def create_picnotes(dirpath, confirm=True, shrink=False): """Attempts to extract notes from all pics found under the given directory and write them to a file.""" dirpath = op.abspath(dirpath) titlepath = os.sep.join(dirpath.split(os.sep)[-2:]) pics = list(auxly.filesys.walkfiles(dirpath, ".(png|jpg)", recurse=True)) if not pics: qprompt.warn("No pics found under directory!") return pics = sort_pics(pics) qprompt.alert(f"Found {len(pics)} pics found under directory.") doc = auxly.filesys.File(dirpath, "pic_notes.adoc") existing_notes = {} if doc.exists(): existing_notes = parse_picnotes(doc) if confirm: if not qprompt.ask_yesno( f"The `pic_notes.adoc` file already exists with {len(existing_notes)} pic notes found, overwrite it?" ): return doc.empty() qprompt.alert(f"Initialized file `{doc.path}`") doc.appendline(f"= PIC NOTES: `{titlepath}`") doc.appendline(":date: " + datetime.now().strftime("%d %B %Y %I:%M%p")) doc.appendline(":toc:") doc.appendline("") doc.appendline("NOTE: Entries sorted by base filename.") doc.appendline("") count = {'reused': 0, 'scanned': 0} for idx, picpath in enumerate(pics, 1): relpath = op.relpath(picpath, dirpath) msg = f"({idx} of {len(pics)})" if relpath in existing_notes.keys() and auxly.filesys.checksum( picpath) == existing_notes[relpath]['md5']: qprompt.alert(f"{msg} Reusing `{picpath}`.") notes = existing_notes[relpath]['note'] if shrink: attempt_shrink(picpath, notes) line = format_adoc_line(relpath, picpath, notes) count['reused'] += 1 else: notes = qprompt.status(f"{msg} Scanning `{picpath}`...", scan_notes, [picpath]) or "NA" if shrink: attempt_shrink(picpath, notes) line = format_adoc_line(relpath, picpath, notes) count['scanned'] += 1 doc.appendline(line) return count
def check_tmplitems(items, tmpldict, topkey=""): missing = [] for key, val in items: if type(val) == model.Dictionary: missing += check_tmplitems( val.items(), tmpldict.get(key, {}), key if not topkey else "%s%s%s" % (topkey, KEYSEP, key)) else: name = key if not topkey else "%s%s%s" % (topkey, KEYSEP, key) try: if key not in tmpldict.keys(): missing.append(name) except: qprompt.warn("Issue checking var `%s`!" % (name)) return missing
def run(): global TESTSERVER if is_running(): warn("App server already running!") return with Cwd("app"): TESTSERVER = start("python app.py", "__temp-flask.log") alert("Application starting...") time.sleep(3) if TESTSERVER.isrunning(): alert("Application started.") browse() else: warn("Issue starting application!") stop()
def talk(text, lang, slow=False, wait=False): def _talk(): """Pronounces the given text in the given language.""" with TALK_LOCK: tpath = op.join(tempfile.gettempdir(), f"__temp-talk-{randomize(6)}.mp3") tts(text=text, lang=lang, slow=slow).save(tpath) playsound(tpath) delete(tpath) try: t = Thread(target=_talk) t.start() if wait: t.join() except: q.warn("Could not talk at this time.")
def run(): global PROCS if is_running(): warn("App server already running!") return with Cwd("app"): if not op.isdir("node_modules"): status("Running NPM install...", silent, ["npm install"]) PROCS.append( start( "node node_modules/rollup/dist/bin/rollup -w -c rollup.config.js" )) PROCS.append(start("python app.py")) alert("Application starting...") time.sleep(3) if all(map(lambda p: p.isrunning(), PROCS)): alert("Application started.") browse() else: warn("Issue starting application!") stop()
def sort_file(path=None): """Alphabetically sort the contents of the given vocabulary txt file.""" if not path: path = ask_file("File to sort") if not path.endswith(".txt"): q.error("Can only sort `.txt` files!") return with open(path) as fi: lines = fi.read().splitlines() sorts = [] okay = True for num, line in enumerate(lines): line = line.strip() try: if not line: continue l1, l2 = line.split(";") l1x = "" l2x = "" if l1.find("(") > -1: l1, l1x = l1.split("(") l1 = l1.strip() l1x = " (" + l1x if l2.find("(") > -1: l2, l2x = l2.split("(") l2 = l2.strip() l2x = " (" + l2x l1 = "/".join(sorted(l1.split("/"))) l2 = "/".join(sorted(l2.split("/"))) sorts.append("%s%s;%s%s" % (l1, l1x, l2, l2x)) except: okay = False temp = unicodedata.normalize('NFKD', line).encode('ascii', 'ignore').strip() q.warn("Issue splitting `%s` line %u: %s" % (path, num, temp)) sorts.append(line) with open(path, "w") as fo: for line in sorted(set(sorts)): fo.write(line + "\n") return okay
def browse(): if not is_running(): warn("Application not running!") return webbrowser.open("http://localhost:5000/")
"""This example deletes all PYC files in the project.""" import auxly import qprompt delfunc = lambda is_test: auxly.filesys.delete("..", "\.pyc$", recurse=True, test=is_test) delfiles = delfunc(True) if len(delfiles): print("Files to delete:") print("\n".join([" " + i for i in delfiles])) if qprompt.ask_yesno("OK to delete?"): if delfunc(False) == delfiles: qprompt.alert("Files deleted.") else: qprompt.warn("Some files not deleted!") else: qprompt.alert("No files to delete.") qprompt.pause()
from qprompt import alert, echo, error, warn, info echo("Just a message.") alert("Heads up!") info("Hmm...") warn("Uh oh...") error("OMG this is bad!") error("REALLY BAD", end="!!!!!!!\n")
def run_build(): try: auxly.open(fr"{OUTDIR}\doctrine2-win32-x64\doctrine2.exe") except: qprompt.warn("Could not find executable!")
def browse(): if not is_running(): warn("Application not running!") return webbrowser.open(f"http://{APPADDRPORT}")