Source code for moulinette.utils.text

import os
import re
import mmap
import binascii


# Pattern searching ----------------------------------------------------





[docs]def searchf(pattern, path, count=0, flags=re.MULTILINE): """Search for pattern in a file Map the file with given path to memory and search for pattern in it content by using the search function. """ with open(path, "r+") as f: data = mmap.mmap(f.fileno(), 0) match = search(pattern, data, count, flags) data.close() return match
# Text formatting ------------------------------------------------------
[docs]def prependlines(text, prepend): """Prepend a string to each line of a text""" lines = text.splitlines(True) return "%s%s" % (prepend, prepend.join(lines))
# Randomize ------------------------------------------------------------
[docs]def random_ascii(length=20): """Return a random ascii string""" return binascii.hexlify(os.urandom(length)).decode("ascii")