signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def create_and_register_access97_db(filename: str,<EOL>dsn: str,<EOL>description: str) -> bool: | fullfilename = os.path.abspath(filename)<EOL>create_string = fullfilename + "<STR_LIT>"<EOL>return (create_user_dsn(access_driver, CREATE_DB3=create_string) and<EOL>register_access_db(filename, dsn, description))<EOL> | (Windows only.)
Creates a Microsoft Access 97 database and registers it with ODBC.
Args:
filename: filename of the database to create
dsn: ODBC data source name to create
description: description of the database
Returns:
bool: was the DSN created? | f14608:m3 |
def create_and_register_access2000_db(filename: str,<EOL>dsn: str,<EOL>description: str) -> bool: | fullfilename = os.path.abspath(filename)<EOL>create_string = fullfilename + "<STR_LIT>"<EOL>return (create_user_dsn(access_driver, CREATE_DB4=create_string) and<EOL>register_access_db(filename, dsn, description))<EOL> | (Windows only.)
Creates a Microsoft Access 2000 database and registers it with ODBC.
Args:
filename: filename of the database to create
dsn: ODBC data source name to create
description: description of the database
Returns:
bool: was the DSN created? | f14608:m4 |
def create_and_register_access_db(filename: str,<EOL>dsn: str,<EOL>description: str) -> bool: | fullfilename = os.path.abspath(filename)<EOL>create_string = fullfilename + "<STR_LIT>"<EOL>return (create_user_dsn(access_driver, CREATE_DB=create_string) and<EOL>register_access_db(filename, dsn, description))<EOL> | (Windows only.)
Creates a Microsoft Access database and registers it with ODBC.
Args:
filename: filename of the database to create
dsn: ODBC data source name to create
description: description of the database
Returns:
bool: was the DSN created? | f14608:m5 |
def sizeof_fmt(num: float, suffix: str = '<STR_LIT:B>') -> str: | for unit in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if abs(num) < <NUM_LIT>:<EOL><INDENT>return "<STR_LIT>" % (num, unit, suffix)<EOL><DEDENT>num /= <NUM_LIT><EOL><DEDENT>return "<STR_LIT>" % (num, '<STR_LIT>', suffix)<EOL> | Formats a number of bytes in a human-readable binary format (e.g. ``2048``
becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841. | f14609:m0 |
def bytes2human(n: Union[int, float],<EOL>format: str = '<STR_LIT>',<EOL>symbols: str = '<STR_LIT>') -> str: | <EOL>nt(n)<EOL>< <NUM_LIT:0>:<EOL>aise ValueError("<STR_LIT>")<EOL>ls = SYMBOLS[symbols]<EOL>x = {}<EOL>, s in enumerate(symbols[<NUM_LIT:1>:]):<EOL>refix[s] = <NUM_LIT:1> << (i + <NUM_LIT:1>) * <NUM_LIT:10><EOL>ymbol in reversed(symbols[<NUM_LIT:1>:]):<EOL>f n >= prefix[symbol]:<EOL><INDENT>value = float(n) / prefix[s... | Converts a number of bytes into a human-readable format.
From http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/.
Args:
n: number of bytes
format: a format specification string
symbols: can be one of ``"customary"``, ``"customary_ext"``, ``"iec"``
or ``"iec_ext"``; ... | f14609:m1 |
def human2bytes(s: str) -> int: | <EOL>t s:<EOL>aise ValueError("<STR_LIT>".format(s))<EOL>eturn int(s)<EOL>t ValueError:<EOL>ass<EOL>= s<EOL><INDENT>"<STR_LIT>"<EOL>s and s[<NUM_LIT:0>:<NUM_LIT:1>].isdigit() or s[<NUM_LIT:0>:<NUM_LIT:1>] == '<STR_LIT:.>':<EOL><DEDENT>um += s[<NUM_LIT:0>]<EOL><INDENT>= s[<NUM_LIT:1>:]<EOL>float(num)<EOL><DEDENT>r = s.s... | Modified from
http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/.
Attempts to guess the string format based on default symbols
set and return the corresponding bytes as an integer.
When unable to recognize the format, :exc:`ValueError` is raised.
>>> human2bytes('0 B')
0
>>> hum... | f14609:m2 |
def cmdline_split(s: str, platform: Union[int, str] = '<STR_LIT>') -> List[str]: | <EOL>atform == '<STR_LIT>':<EOL>latform = (sys.platform != '<STR_LIT:win32>') <EOL>atform == <NUM_LIT:1>: <EOL>e_cmd_lex = r'''<STR_LIT>''' <EOL>platform == <NUM_LIT:0>: <EOL>e_cmd_lex = r'''<STR_LIT>''' <EOL>aise AssertionError('<STR_LIT>' % platform)<EOL>= []<EOL>= None <EOL>s, qss, esc, pipe, word, white, fai... | As per
https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex.
Multi-platform variant of ``shlex.split()`` for command-line splitting.
For use with ``subprocess``, for ``argv`` injection etc. Using fast REGEX.
Args:
s:
string to split
platform:
- ``'this'`... | f14610:m0 |
def cmdline_quote(args: List[str]) -> str: | <EOL>return subprocess.list2cmdline(args)<EOL> | Convert a list of command-line arguments to a suitably quoted command-line
string that should be copy/pastable into a comand prompt. | f14610:m1 |
def str2bool(v: str) -> bool: | <EOL>v.lower()<EOL><INDENT>in ('<STR_LIT:yes>', '<STR_LIT:true>', '<STR_LIT:t>', '<STR_LIT:y>', '<STR_LIT:1>'):<EOL><DEDENT>eturn True<EOL>lv in ('<STR_LIT>', '<STR_LIT:false>', '<STR_LIT:f>', '<STR_LIT:n>', '<STR_LIT:0>'):<EOL>eturn False<EOL>aise ArgumentTypeError('<STR_LIT>')<EOL> | ``argparse`` type that maps strings in case-insensitive fashion like this:
.. code-block:: none
argument strings value
------------------------------- -----
'yes', 'true', 't', 'y', '1' True
'no', 'false', 'f', 'n', '0' False
From
https://stackoverflow.com/questions/15008758/pars... | f14612:m0 |
def positive_int(value: str) -> int: | try:<EOL><INDENT>ivalue = int(value)<EOL>assert ivalue > <NUM_LIT:0><EOL><DEDENT>except (AssertionError, TypeError, ValueError):<EOL><INDENT>raise ArgumentTypeError(<EOL>"<STR_LIT>".format(value))<EOL><DEDENT>return ivalue<EOL> | ``argparse`` argument type that checks that its value is a positive
integer. | f14612:m1 |
def nonnegative_int(value: str) -> int: | try:<EOL><INDENT>ivalue = int(value)<EOL>assert ivalue >= <NUM_LIT:0><EOL><DEDENT>except (AssertionError, TypeError, ValueError):<EOL><INDENT>raise ArgumentTypeError(<EOL>"<STR_LIT>".format(value))<EOL><DEDENT>return ivalue<EOL> | ``argparse`` argument type that checks that its value is a non-negative
integer. | f14612:m2 |
def percentage(value: str) -> float: | try:<EOL><INDENT>fvalue = float(value)<EOL>assert <NUM_LIT:0> <= fvalue <= <NUM_LIT:100><EOL><DEDENT>except (AssertionError, TypeError, ValueError):<EOL><INDENT>raise ArgumentTypeError(<EOL>"<STR_LIT>".format(value))<EOL><DEDENT>return fvalue<EOL> | ``argparse`` argument type that checks that its value is a percentage (in
the sense of a float in the range [0, 100]). | f14612:m3 |
def __init__(self,<EOL>map_separator: str = "<STR_LIT::>",<EOL>pair_separator: str = "<STR_LIT:U+002C>",<EOL>strip: bool = True,<EOL>from_type: Type = str,<EOL>to_type: Type = str) -> None: | self.map_separator = map_separator<EOL>self.pair_separator = pair_separator<EOL>self.strip = strip<EOL>self.from_type = from_type<EOL>self.to_type = to_type<EOL> | Args:
map_separator:
string that separates the "from" and "to" members of a pair
pair_separator:
string that separates different pairs
strip:
strip whitespace after splitting?
from_type:
type to coerce "from" values to; e.g. ``str``, ``int``
to_type:
type to c... | f14612:c2:m0 |
def hash_password(plaintextpw: str,<EOL>log_rounds: int = BCRYPT_DEFAULT_LOG_ROUNDS) -> str: | salt = bcrypt.gensalt(log_rounds) <EOL>hashedpw = bcrypt.hashpw(plaintextpw, salt)<EOL>return hashedpw<EOL> | Makes a hashed password (using a new salt) using ``bcrypt``.
The hashed password includes the salt at its start, so no need to store a
separate salt. | f14613:m0 |
def is_password_valid(plaintextpw: str, storedhash: str) -> bool: | <EOL>if storedhash is None:<EOL><INDENT>storedhash = "<STR_LIT>"<EOL><DEDENT>storedhash = str(storedhash)<EOL>if plaintextpw is None:<EOL><INDENT>plaintextpw = "<STR_LIT>"<EOL><DEDENT>plaintextpw = str(plaintextpw)<EOL>try:<EOL><INDENT>h = bcrypt.hashpw(plaintextpw, storedhash)<EOL><DEDENT>except ValueError: <EOL><IND... | Checks if a plaintext password matches a stored hash.
Uses ``bcrypt``. The stored hash includes its own incorporated salt. | f14613:m1 |
def convert_to_bool(x: Any, default: bool = None) -> bool: | if isinstance(x, bool):<EOL><INDENT>return x<EOL><DEDENT>if not x: <EOL><INDENT>return default<EOL><DEDENT>try:<EOL><INDENT>return int(x) != <NUM_LIT:0><EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return float(x) != <NUM_LIT:0><EOL><DEDENT>except (TypeError, ValueError):<E... | Transforms its input to a ``bool`` (or returns ``default`` if ``x`` is
falsy but not itself a boolean). Accepts various common string versions. | f14614:m0 |
def convert_to_int(x: Any, default: int = None) -> int: | try:<EOL><INDENT>return int(x)<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>return default<EOL><DEDENT> | Transforms its input into an integer, or returns ``default``. | f14614:m1 |
def convert_attrs_to_bool(obj: Any,<EOL>attrs: Iterable[str],<EOL>default: bool = None) -> None: | for a in attrs:<EOL><INDENT>setattr(obj, a, convert_to_bool(getattr(obj, a), default=default))<EOL><DEDENT> | Applies :func:`convert_to_bool` to the specified attributes of an object,
modifying it in place. | f14614:m2 |
def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None: | for a in attrs:<EOL><INDENT>value = getattr(obj, a)<EOL>if value is None:<EOL><INDENT>continue<EOL><DEDENT>setattr(obj, a, value.upper())<EOL><DEDENT> | Converts the specified attributes of an object to upper case, modifying
the object in place. | f14614:m3 |
def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None: | for a in attrs:<EOL><INDENT>value = getattr(obj, a)<EOL>if value is None:<EOL><INDENT>continue<EOL><DEDENT>setattr(obj, a, value.lower())<EOL><DEDENT> | Converts the specified attributes of an object to lower case, modifying
the object in place. | f14614:m4 |
def convert_attrs_to_int(obj: Any,<EOL>attrs: Iterable[str],<EOL>default: int = None) -> None: | for a in attrs:<EOL><INDENT>value = convert_to_int(getattr(obj, a), default=default)<EOL>setattr(obj, a, value)<EOL><DEDENT> | Applies :func:`convert_to_int` to the specified attributes of an object,
modifying it in place. | f14614:m5 |
def hex_xformat_encode(v: bytes) -> str: | return "<STR_LIT>".format(binascii.hexlify(v).decode("<STR_LIT:ascii>"))<EOL> | Encode its input in ``X'{hex}'`` format.
Example:
.. code-block:: python
special_hex_encode(b"hello") == "X'68656c6c6f'" | f14614:m6 |
def hex_xformat_decode(s: str) -> Optional[bytes]: | if len(s) < <NUM_LIT:3> or not s.startswith("<STR_LIT>") or not s.endswith("<STR_LIT:'>"):<EOL><INDENT>return None<EOL><DEDENT>return binascii.unhexlify(s[<NUM_LIT:2>:-<NUM_LIT:1>])<EOL> | Reverse :func:`hex_xformat_encode`.
The parameter is a hex-encoded BLOB like
.. code-block:: none
"X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'"
Original purpose and notes:
- SPECIAL HANDLING for BLOBs: a string like ``X'01FF'`` means a hex-encoded
BLOB. Titanium is rubbish at BLOBs, so we encode them as spec... | f14614:m7 |
def base64_64format_encode(v: bytes) -> str: | return "<STR_LIT>".format(base64.b64encode(v).decode('<STR_LIT:ascii>'))<EOL> | Encode in ``64'{base64encoded}'`` format.
Example:
.. code-block:: python
base64_64format_encode(b"hello") == "64'aGVsbG8='" | f14614:m8 |
def base64_64format_decode(s: str) -> Optional[bytes]: | if len(s) < <NUM_LIT:4> or not s.startswith("<STR_LIT>") or not s.endswith("<STR_LIT:'>"):<EOL><INDENT>return None<EOL><DEDENT>return base64.b64decode(s[<NUM_LIT:3>:-<NUM_LIT:1>])<EOL> | Reverse :func:`base64_64format_encode`.
Original purpose and notes:
- THIS IS ANOTHER WAY OF DOING BLOBS: base64 encoding, e.g. a string like
``64'cGxlYXN1cmUu'`` is a base-64-encoded BLOB (the ``64'...'`` bit is my
representation).
- regex from http://stackoverflow.com/questions/475074
- better one from http://w... | f14614:m9 |
def create_base64encoded_randomness(num_bytes: int) -> str: | randbytes = os.urandom(num_bytes) <EOL>return base64.urlsafe_b64encode(randbytes).decode('<STR_LIT:ascii>')<EOL> | Create and return ``num_bytes`` of random data.
The result is encoded in a string with URL-safe ``base64`` encoding.
Used (for example) to generate session tokens.
Which generator to use? See
https://cryptography.io/en/latest/random-numbers/.
Do NOT use these methods:
.. code-block:: python
randbytes = M2Cryp... | f14615:m0 |
def import_submodules(package: Union[str, ModuleType],<EOL>base_package_for_relative_import: str = None,<EOL>recursive: bool = True) -> Dict[str, ModuleType]: | <EOL>if isinstance(package, str):<EOL><INDENT>package = importlib.import_module(package,<EOL>base_package_for_relative_import)<EOL><DEDENT>results = {}<EOL>for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):<EOL><INDENT>full_name = package.__name__ + '<STR_LIT:.>' + name<EOL>log.debug("<STR_LIT>", full... | Import all submodules of a module, recursively, including subpackages.
Args:
package: package (name or actual module)
base_package_for_relative_import: path to prepend?
recursive: import submodules too?
Returns:
dict: mapping from full module name to module | f14616:m0 |
def is_builtin_module(module: ModuleType) -> bool: | assert inspect.ismodule(module)<EOL>return not hasattr(module, "<STR_LIT>")<EOL> | Is this module a built-in module, like ``os``?
Method is as per :func:`inspect.getfile`. | f14616:m1 |
def is_c_extension(module: ModuleType) -> bool: | <EOL>t inspect.ismodule(module), '<STR_LIT>'.format(module)<EOL>this module was loaded by a PEP <NUM_LIT>-compliant CPython-specific loader<EOL>ding only C extensions, this module is a C extension.<EOL>instance(getattr(module, '<STR_LIT>', None), ExtensionFileLoader):<EOL>eturn True<EOL>it'<STR_LIT>'s not a C extension... | Modified from
https://stackoverflow.com/questions/20339053/in-python-how-can-one-tell-if-a-module-comes-from-a-c-extension.
``True`` only if the passed module is a C extension implemented as a
dynamically linked shared library specific to the current platform.
Args:
module: Previously imported module object to be... | f14616:m3 |
def contains_c_extension(module: ModuleType,<EOL>import_all_submodules: bool = True,<EOL>include_external_imports: bool = False,<EOL>seen: List[ModuleType] = None) -> bool: | <EOL>t inspect.ismodule(module), '<STR_LIT>'.format(module)<EOL>en is None: <EOL>een = [] <EOL>dule in seen: <EOL><INDENT>already inspected; avoid infinite loops<EOL><DEDENT>eturn False<EOL>append(module)<EOL>ck the thing we were asked about<EOL>ext = is_c_extension(module)<EOL>nfo("<STR_LIT>", module, is_c_ext)<EOL... | Extends :func:`is_c_extension` by asking: is this module, or any of its
submodules, a C extension?
Args:
module: Previously imported module object to be tested.
import_all_submodules: explicitly import all submodules of this module?
include_external_imports: check modules in other packages that this
... | f14616:m4 |
def which_with_envpath(executable: str, env: Dict[str, str]) -> str: | oldpath = os.environ.get("<STR_LIT>", "<STR_LIT>")<EOL>os.environ["<STR_LIT>"] = env.get("<STR_LIT>")<EOL>which = shutil.which(executable)<EOL>os.environ["<STR_LIT>"] = oldpath<EOL>return which<EOL> | Performs a :func:`shutil.which` command using the PATH from the specified
environment.
Reason: when you use ``run([executable, ...], env)`` and therefore
``subprocess.run([executable, ...], env=env)``, the PATH that's searched
for ``executable`` is the parent's, not the new child's -- so you have to
find the executabl... | f14617:m0 |
def require_executable(executable: str) -> None: | if shutil.which(executable):<EOL><INDENT>return<EOL><DEDENT>errmsg = "<STR_LIT>" + executable<EOL>log.critical(errmsg)<EOL>raise FileNotFoundError(errmsg)<EOL> | If ``executable`` is not found by :func:`shutil.which`, raise
:exc:`FileNotFoundError`. | f14617:m1 |
def mkdir_p(path: str) -> None: | log.debug("<STR_LIT>" + path)<EOL>os.makedirs(path, exist_ok=True)<EOL> | Makes a directory, and any intermediate (parent) directories if required.
This is the UNIX ``mkdir -p DIRECTORY`` command; of course, we use
:func:`os.makedirs` instead, for portability. | f14617:m2 |
@contextmanager<EOL>def pushd(directory: str) -> None: | previous_dir = os.getcwd()<EOL>os.chdir(directory)<EOL>yield<EOL>os.chdir(previous_dir)<EOL> | Context manager: changes directory and preserves the original on exit.
Example:
.. code-block:: python
with pushd(new_directory):
# do things | f14617:m3 |
def preserve_cwd(func: Callable) -> Callable: | <EOL>def decorator(*args_, **kwargs) -> Any:<EOL><INDENT>cwd = os.getcwd()<EOL>result = func(*args_, **kwargs)<EOL>os.chdir(cwd)<EOL>return result<EOL><DEDENT>return decorator<EOL> | Decorator to preserve the current working directory in calls to the
decorated function.
Example:
.. code-block:: python
@preserve_cwd
def myfunc():
os.chdir("/faraway")
os.chdir("/home")
myfunc()
assert os.getcwd() == "/home" | f14617:m4 |
def root_path() -> str: | <EOL>return os.path.abspath(os.sep)<EOL> | Returns the system root directory. | f14617:m5 |
def copyglob(src: str, dest: str, allow_nothing: bool = False,<EOL>allow_nonfiles: bool = False) -> None: | something = False<EOL>for filename in glob.glob(src):<EOL><INDENT>if allow_nonfiles or os.path.isfile(filename):<EOL><INDENT>shutil.copy(filename, dest)<EOL>something = True<EOL><DEDENT><DEDENT>if something or allow_nothing:<EOL><INDENT>return<EOL><DEDENT>raise ValueError("<STR_LIT>".format(src))<EOL> | Copies files whose filenames match the glob src" into the directory
"dest". Raises an error if no files are copied, unless allow_nothing is
True.
Args:
src: source glob (e.g. ``/somewhere/*.txt``)
dest: destination directory
allow_nothing: don't raise an exception if no files are found
allow_nonfiles: ... | f14617:m6 |
def moveglob(src: str, dest: str, allow_nothing: bool = False,<EOL>allow_nonfiles: bool = False) -> None: | something = False<EOL>for filename in glob.glob(src):<EOL><INDENT>if allow_nonfiles or os.path.isfile(filename):<EOL><INDENT>shutil.move(filename, dest)<EOL>something = True<EOL><DEDENT><DEDENT>if something or allow_nothing:<EOL><INDENT>return<EOL><DEDENT>raise ValueError("<STR_LIT>".format(src))<EOL> | As for :func:`copyglob`, but moves instead. | f14617:m7 |
def copy_tree_root(src_dir: str, dest_parent: str) -> None: | dirname = os.path.basename(os.path.normpath(src_dir))<EOL>dest_dir = os.path.join(dest_parent, dirname)<EOL>shutil.copytree(src_dir, dest_dir)<EOL> | Copies a directory ``src_dir`` into the directory ``dest_parent``.
That is, with a file structure like:
.. code-block:: none
/source/thing/a.txt
/source/thing/b.txt
/source/thing/somedir/c.txt
the command
.. code-block:: python
copy_tree_root("/source/thing", "/dest")
ends up creating
.. code-blo... | f14617:m8 |
def copy_tree_contents(srcdir: str, destdir: str,<EOL>destroy: bool = False) -> None: | log.info("<STR_LIT>", srcdir, destdir)<EOL>if os.path.exists(destdir):<EOL><INDENT>if not destroy:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not os.path.isdir(destdir):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>log.debug("<STR_LIT>")<EOL>rmtree(destdir)<EOL>log.debug("<STR_LIT>")<EOL><DEDENT>... | Recursive copy. Unlike :func:`copy_tree_root`, :func:`copy_tree_contents`
works as follows. With the file structure:
.. code-block:: none
/source/thing/a.txt
/source/thing/b.txt
/source/thing/somedir/c.txt
the command
.. code-block:: python
copy_tree_contents("/source/thing", "/dest")
ends up crea... | f14617:m9 |
def rmglob(pattern: str) -> None: | for f in glob.glob(pattern):<EOL><INDENT>os.remove(f)<EOL><DEDENT> | Deletes all files whose filename matches the glob ``pattern`` (via
:func:`glob.glob`). | f14617:m10 |
def purge(path: str, pattern: str) -> None: | for f in find(pattern, path):<EOL><INDENT>log.info("<STR_LIT>", f)<EOL>os.remove(f)<EOL><DEDENT> | Deletes all files in ``path`` matching ``pattern`` (via
:func:`fnmatch.fnmatch`). | f14617:m11 |
def delete_files_within_dir(directory: str, filenames: List[str]) -> None: | for dirpath, dirnames, fnames in os.walk(directory):<EOL><INDENT>for f in fnames:<EOL><INDENT>if f in filenames:<EOL><INDENT>fullpath = os.path.join(dirpath, f)<EOL>log.debug("<STR_LIT>", fullpath)<EOL>os.remove(fullpath)<EOL><DEDENT><DEDENT><DEDENT> | Delete files within ``directory`` whose filename *exactly* matches one of
``filenames``. | f14617:m12 |
def shutil_rmtree_onerror(func: Callable[[str], None],<EOL>path: str,<EOL>exc_info: EXC_INFO_TYPE) -> None: | <EOL>t os.access(path, os.W_OK):<EOL><INDENT>Is the error an access error?<EOL><DEDENT>s.chmod(path, stat.S_IWUSR)<EOL>unc(path)<EOL>xc = exc_info[<NUM_LIT:1>]<EOL>aise exc<EOL> | Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage: ``shutil.rmtree(path, onerror=shutil_rmtree_onerror)``
See
https://stackoverflow.com/questions/2656322/... | f14617:m13 |
def rmtree(directory: str) -> None: | log.debug("<STR_LIT>", directory)<EOL>shutil.rmtree(directory, onerror=shutil_rmtree_onerror)<EOL> | Deletes a directory tree. | f14617:m14 |
def chown_r(path: str, user: str, group: str) -> None: | for root, dirs, files in os.walk(path):<EOL><INDENT>for x in dirs:<EOL><INDENT>shutil.chown(os.path.join(root, x), user, group)<EOL><DEDENT>for x in files:<EOL><INDENT>shutil.chown(os.path.join(root, x), user, group)<EOL><DEDENT><DEDENT> | Performs a recursive ``chown``.
Args:
path: path to walk down
user: user name or ID
group: group name or ID
As per http://stackoverflow.com/questions/2853723 | f14617:m15 |
def chmod_r(root: str, permission: int) -> None: | os.chmod(root, permission)<EOL>for dirpath, dirnames, filenames in os.walk(root):<EOL><INDENT>for d in dirnames:<EOL><INDENT>os.chmod(os.path.join(dirpath, d), permission)<EOL><DEDENT>for f in filenames:<EOL><INDENT>os.chmod(os.path.join(dirpath, f), permission)<EOL><DEDENT><DEDENT> | Recursive ``chmod``.
Args:
root: directory to walk down
permission: e.g. ``e.g. stat.S_IWUSR`` | f14617:m16 |
def find(pattern: str, path: str) -> List[str]: | result = []<EOL>for root, dirs, files in os.walk(path):<EOL><INDENT>for name in files:<EOL><INDENT>if fnmatch.fnmatch(name, pattern):<EOL><INDENT>result.append(os.path.join(root, name))<EOL><DEDENT><DEDENT><DEDENT>return result<EOL> | Finds files in ``path`` whose filenames match ``pattern`` (via
:func:`fnmatch.fnmatch`). | f14617:m17 |
def find_first(pattern: str, path: str) -> str: | try:<EOL><INDENT>return find(pattern, path)[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>log.critical('''<STR_LIT>''', pattern, path)<EOL>raise<EOL><DEDENT> | Finds first file in ``path`` whose filename matches ``pattern`` (via
:func:`fnmatch.fnmatch`), or raises :exc:`IndexError`. | f14617:m18 |
def gen_filenames(starting_filenames: List[str],<EOL>recursive: bool) -> Generator[str, None, None]: | for base_filename in starting_filenames:<EOL><INDENT>if os.path.isfile(base_filename):<EOL><INDENT>yield os.path.abspath(base_filename)<EOL><DEDENT>elif os.path.isdir(base_filename) and recursive:<EOL><INDENT>for dirpath, dirnames, filenames in os.walk(base_filename):<EOL><INDENT>for fname in filenames:<EOL><INDENT>yie... | From a starting list of files and/or directories, generates filenames of
all files in the list, and (if ``recursive`` is set) all files within
directories in the list.
Args:
starting_filenames: files and/or directories
recursive: walk down any directories in the starting list, recursively?
Yields:
each fi... | f14617:m19 |
def exists_locked(filepath: str) -> Tuple[bool, bool]: | exists = False<EOL>locked = None<EOL>file_object = None<EOL>if os.path.exists(filepath):<EOL><INDENT>exists = True<EOL>locked = True<EOL>try:<EOL><INDENT>buffer_size = <NUM_LIT:8><EOL>file_object = open(filepath, '<STR_LIT:a>', buffer_size)<EOL>if file_object:<EOL><INDENT>locked = False <EOL><DEDENT><DEDENT>except IOE... | Checks if a file is locked by opening it in append mode.
(If no exception is thrown in that situation, then the file is not locked.)
Args:
filepath: file to check
Returns:
tuple: ``(exists, locked)``
See https://www.calazan.com/how-to-check-if-a-file-is-locked-in-python/. | f14617:m20 |
def relative_filename_within_dir(filename: str, directory: str) -> str: | filename = os.path.abspath(filename)<EOL>directory = os.path.abspath(directory)<EOL>if os.path.commonpath([directory, filename]) != directory:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>return os.path.relpath(filename, start=directory)<EOL> | Starting with a (typically absolute) ``filename``, returns the part of the
filename that is relative to the directory ``directory``.
If the file is *not* within the directory, returns an empty string. | f14617:m21 |
def ctrl_c_trapper(signum: int, stackframe) -> None: | log.critical("<STR_LIT>", signum)<EOL> | Logs that ``CTRL-C`` has been pressed but does nothing else. | f14618:m0 |
def ctrl_break_trapper(signum: int, stackframe) -> None: | log.critical("<STR_LIT>",<EOL>signum)<EOL> | Logs that ``CTRL-BREAK`` has been pressed but does nothing else. | f14618:m1 |
def sigterm_trapper(signum: int, stackframe) -> None: | log.critical("<STR_LIT>", signum)<EOL> | Logs that ``SIGTERM`` has been received but does nothing else. | f14618:m2 |
def trap_ctrl_c_ctrl_break() -> None: | <EOL>l.signal(signal.SIGINT, ctrl_c_trapper)<EOL>l.signal(signal.SIGTERM, sigterm_trapper)<EOL>atform.system() == '<STR_LIT>':<EOL><INDENT>SIGBREAK isn't in the Linux signal module<EOL>noinspection PyUnresolvedReferences<EOL><DEDENT>ignal.signal(signal.SIGBREAK, ctrl_break_trapper)<EOL> | Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing
anything.
See
- https://docs.python.org/3/library/signal.html#signal.SIG_IGN
- https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx
- https://msdn.microsoft.com/en-us/library/windows/desktop/ms682541(v=vs.85).aspx
Under Windows, the only options ar... | f14618:m3 |
@atexit.register<EOL>def kill_child_processes() -> None: | timeout_sec = <NUM_LIT:5><EOL>for p in processes:<EOL><INDENT>try:<EOL><INDENT>p.wait(timeout_sec)<EOL><DEDENT>except TimeoutExpired:<EOL><INDENT>p.kill()<EOL><DEDENT><DEDENT> | Kills children of this process that were registered in the
:data:`processes` variable.
Use with ``@atexit.register``. | f14621:m0 |
def fail() -> None: | print("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:1>)<EOL> | Call when a child process has failed, and this will print an error
message to ``stdout`` and execute ``sys.exit(1)`` (which will, in turn,
call any ``atexit`` handler to kill children of this process). | f14621:m1 |
def check_call_process(args: List[str]) -> None: | log.debug("<STR_LIT>", args)<EOL>check_call(args)<EOL> | Logs the command arguments, then executes the command via
:func:`subprocess.check_call`. | f14621:m2 |
def start_process(args: List[str],<EOL>stdin: Any = None,<EOL>stdout: Any = None,<EOL>stderr: Any = None) -> Popen: | log.debug("<STR_LIT>", args)<EOL>global processes<EOL>global proc_args_list<EOL>proc = Popen(args, stdin=stdin, stdout=stdout, stderr=stderr)<EOL>processes.append(proc)<EOL>proc_args_list.append(args)<EOL>return proc<EOL> | Launch a child process and record it in our :data:`processes` variable.
Args:
args: program and its arguments, as a list
stdin: typically None
stdout: use None to perform no routing, which preserves console colour!
Otherwise, specify somewhere to route stdout. See subprocess
documentation. ... | f14621:m3 |
def wait_for_processes(die_on_failure: bool = True,<EOL>timeout_sec: float = <NUM_LIT:1>) -> None: | global processes<EOL>global proc_args_list<EOL>n = len(processes)<EOL>Pool(n).map(print_lines, processes) <EOL>something_running = True<EOL>while something_running:<EOL><INDENT>something_running = False<EOL>for i, p in enumerate(processes):<EOL><INDENT>try:<EOL><INDENT>retcode = p.wait(timeout=timeout_sec)<EOL>if retc... | Wait for child processes (catalogued in :data:`processes`) to finish.
If ``die_on_failure`` is ``True``, then whenever a subprocess returns
failure, all are killed.
If ``timeout_sec`` is None, the function waits for its first process to
complete, then waits for the second, etc. So a subprocess dying does not
trigger ... | f14621:m4 |
def print_lines(process: Popen) -> None: | out, err = process.communicate()<EOL>if out:<EOL><INDENT>for line in out.decode("<STR_LIT:utf-8>").splitlines():<EOL><INDENT>print(line)<EOL><DEDENT><DEDENT>if err:<EOL><INDENT>for line in err.decode("<STR_LIT:utf-8>").splitlines():<EOL><INDENT>print(line)<EOL><DEDENT><DEDENT> | Let a subprocess :func:`communicate`, then write both its ``stdout`` and
its ``stderr`` to our ``stdout``. | f14621:m5 |
def run_multiple_processes(args_list: List[List[str]],<EOL>die_on_failure: bool = True) -> None: | for procargs in args_list:<EOL><INDENT>start_process(procargs)<EOL><DEDENT>wait_for_processes(die_on_failure=die_on_failure)<EOL> | Fire up multiple processes, and wait for them to finihs.
Args:
args_list: command arguments for each process
die_on_failure: see :func:`wait_for_processes` | f14621:m6 |
def mimic_user_input(<EOL>args: List[str],<EOL>source_challenge_response: List[Tuple[SubprocSource,<EOL>str,<EOL>Union[str, SubprocCommand]]],<EOL>line_terminators: List[str] = None,<EOL>print_stdout: bool = False,<EOL>print_stderr: bool = False,<EOL>print_stdin: bool = False,<EOL>stdin_encoding: str = None,<EOL>stdout... | <EOL>terminators = line_terminators or ["<STR_LIT:\n>"] <EOL>_encoding = stdin_encoding or sys.getdefaultencoding()<EOL>t_encoding = stdout_encoding or sys.getdefaultencoding()<EOL>nch the command<EOL>open(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=<NUM_LIT:0>)<EOL>nch the asynchronous readers of stdout and s... | r"""
Run an external command. Pretend to be a human by sending text to the
subcommand (responses) when the external command sends us triggers
(challenges).
This is a bit nasty.
Args:
args: command-line arguments
source_challenge_response: list of tuples of the format ``(challsrc,
... | f14621:m7 |
def __init__(self,<EOL>fd: BinaryIO,<EOL>queue: Queue,<EOL>encoding: str,<EOL>line_terminators: List[str] = None,<EOL>cmdargs: List[str] = None,<EOL>suppress_decoding_errors: bool = True) -> None: | assert isinstance(queue, Queue)<EOL>assert callable(fd.readline)<EOL>super().__init__()<EOL>self._fd = fd<EOL>self._queue = queue<EOL>self._encoding = encoding<EOL>self._line_terminators = line_terminators or ["<STR_LIT:\n>"] <EOL>self._cmdargs = cmdargs or [] <EOL>self._suppress_decoding_errors = suppress_decoding_e... | Args:
fd: file-like object to read from
queue: queue to write to
encoding: encoding to use when reading from the file
line_terminators: valid line terminators
cmdargs: for display purposes only: command that produced/is
producing the file-like object
suppress_decoding_errors: trap any ``... | f14621:c2:m0 |
def run(self) -> None: | fd = self._fd<EOL>encoding = self._encoding<EOL>line_terminators = self._line_terminators<EOL>queue = self._queue<EOL>buf = "<STR_LIT>"<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>c = fd.read(<NUM_LIT:1>).decode(encoding)<EOL><DEDENT>except UnicodeDecodeError as e:<EOL><INDENT>log.warning("<STR_LIT>", self._cmdargs, e... | Read lines and put them on the queue. | f14621:c2:m1 |
def eof(self) -> bool: | return not self.is_alive() and self._queue.empty()<EOL> | Check whether there is no more content to expect. | f14621:c2:m2 |
def does_unrtf_support_quiet() -> bool: | required_unrtf_version = Version("<STR_LIT>")<EOL>unrtf_filename = shutil.which('<STR_LIT>')<EOL>if not unrtf_filename:<EOL><INDENT>return False<EOL><DEDENT>p = subprocess.Popen(["<STR_LIT>", "<STR_LIT>"],<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE)<EOL>_, err_bytes = p.communicate()<EOL>text = err_bytes.de... | The unrtf tool supports the '--quiet' argument from a version that I'm not
quite sure of, where ``0.19.3 < version <= 0.21.9``. We check against
0.21.9 here. | f14622:m0 |
def update_external_tools(tooldict: Dict[str, str]) -> None: | global tools<EOL>tools.update(tooldict)<EOL> | Update the global map of tools.
Args:
tooldict: dictionary whose keys are tools names and whose values are
paths to the executables | f14622:m1 |
def get_filelikeobject(filename: str = None,<EOL>blob: bytes = None) -> BinaryIO: | if not filename and not blob:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if filename and blob:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if filename:<EOL><INDENT>return open(filename, '<STR_LIT:rb>')<EOL><DEDENT>else:<EOL><INDENT>return io.BytesIO(blob)<EOL><DEDENT> | Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob: for specifying via an in-memory ``bytes`` object
Returns:
a :class:`BinaryIO` object | f14622:m2 |
def get_file_contents(filename: str = None, blob: bytes = None) -> bytes: | if not filename and not blob:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if filename and blob:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if blob:<EOL><INDENT>return blob<EOL><DEDENT>with open(filename, '<STR_LIT:rb>') as f:<EOL><INDENT>return f.read()<EOL><DEDENT> | Returns the binary contents of a file, or of a BLOB. | f14622:m3 |
def get_chardet_encoding(binary_contents: bytes) -> Optional[str]: | if not binary_contents:<EOL><INDENT>return None<EOL><DEDENT>if chardet is None or UniversalDetector is None:<EOL><INDENT>log.warning("<STR_LIT>")<EOL>return None<EOL><DEDENT>detector = UniversalDetector()<EOL>for byte_line in binary_contents.split(b"<STR_LIT:\n>"):<EOL><INDENT>detector.feed(byte_line)<EOL>if detector.d... | Guess the character set encoding of the specified ``binary_contents``. | f14622:m4 |
def get_file_contents_text(<EOL>filename: str = None, blob: bytes = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | binary_contents = get_file_contents(filename=filename, blob=blob)<EOL>if config.encoding:<EOL><INDENT>try:<EOL><INDENT>return binary_contents.decode(config.encoding)<EOL><DEDENT>except ValueError: <EOL><INDENT>pass<EOL><DEDENT><DEDENT>sysdef = sys.getdefaultencoding()<EOL>if sysdef != config.encoding:<EOL><INDENT>try:... | Returns the string contents of a file, or of a BLOB. | f14622:m5 |
def get_cmd_output(*args, encoding: str = SYS_ENCODING) -> str: | log.debug("<STR_LIT>", args)<EOL>p = subprocess.Popen(args, stdout=subprocess.PIPE)<EOL>stdout, stderr = p.communicate()<EOL>return stdout.decode(encoding, errors='<STR_LIT:ignore>')<EOL> | Returns text output of a command. | f14622:m6 |
def get_cmd_output_from_stdin(stdint_content_binary: bytes,<EOL>*args, encoding: str = SYS_ENCODING) -> str: | p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)<EOL>stdout, stderr = p.communicate(input=stdint_content_binary)<EOL>return stdout.decode(encoding, errors='<STR_LIT:ignore>')<EOL> | Returns text output of a command, passing binary data in via stdin. | f14622:m7 |
def convert_pdf_to_txt(filename: str = None, blob: bytes = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | pdftotext = tools['<STR_LIT>']<EOL>if pdftotext: <EOL><INDENT>if filename:<EOL><INDENT>return get_cmd_output(pdftotext, filename, '<STR_LIT:->')<EOL><DEDENT>else:<EOL><INDENT>return get_cmd_output_from_stdin(blob, pdftotext, '<STR_LIT:->', '<STR_LIT:->')<EOL><DEDENT><DEDENT>elif pdfminer: <EOL><INDENT>with get_fileli... | Converts a PDF file to text.
Pass either a filename or a binary object. | f14622:m8 |
def availability_pdf() -> bool: | pdftotext = tools['<STR_LIT>']<EOL>if pdftotext:<EOL><INDENT>return True<EOL><DEDENT>elif pdfminer:<EOL><INDENT>log.warning("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Is a PDF-to-text tool available? | f14622:m9 |
def gen_xml_files_from_docx(fp: BinaryIO) -> Iterator[str]: | try:<EOL><INDENT>z = zipfile.ZipFile(fp)<EOL>filelist = z.namelist()<EOL>for filename in filelist:<EOL><INDENT>if DOCX_HEADER_FILE_REGEX.match(filename):<EOL><INDENT>yield z.read(filename).decode("<STR_LIT:utf8>")<EOL><DEDENT><DEDENT>yield z.read(DOCX_DOC_FILE)<EOL>for filename in filelist:<EOL><INDENT>if DOCX_FOOTER_F... | Generate XML files (as strings) from a DOCX file.
Args:
fp: :class:`BinaryIO` object for reading the ``.DOCX`` file
Yields:
the string contents of each individual XML file within the ``.DOCX``
file
Raises:
zipfile.BadZipFile: if the zip is unreadable (encrypted?) | f14622:m11 |
def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str: | root = ElementTree.fromstring(xml)<EOL>return docx_text_from_xml_node(root, <NUM_LIT:0>, config)<EOL> | Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string | f14622:m12 |
def docx_text_from_xml_node(node: ElementTree.Element,<EOL>level: int,<EOL>config: TextProcessingConfig) -> str: | text = '<STR_LIT>'<EOL>if node.tag == DOCX_TEXT:<EOL><INDENT>text += node.text or '<STR_LIT>'<EOL><DEDENT>elif node.tag == DOCX_TAB:<EOL><INDENT>text += '<STR_LIT:\t>'<EOL><DEDENT>elif node.tag in DOCX_NEWLINES:<EOL><INDENT>text += '<STR_LIT:\n>'<EOL><DEDENT>elif node.tag == DOCX_NEWPARA:<EOL><INDENT>text += '<STR_LIT>... | Returns text from an XML node within a DOCX file.
Args:
node: an XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string | f14622:m13 |
def docx_table_from_xml_node(table_node: ElementTree.Element,<EOL>level: int,<EOL>config: TextProcessingConfig) -> str: | table = CustomDocxTable()<EOL>for row_node in table_node:<EOL><INDENT>if row_node.tag != DOCX_TABLE_ROW:<EOL><INDENT>continue<EOL><DEDENT>table.new_row()<EOL>for cell_node in row_node:<EOL><INDENT>if cell_node.tag != DOCX_TABLE_CELL:<EOL><INDENT>continue<EOL><DEDENT>table.new_cell()<EOL>for para_node in cell_node:<EOL>... | Converts an XML node representing a DOCX table into a textual
representation.
Args:
table_node: XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
string representation | f14622:m14 |
def docx_process_simple_text(text: str, width: int) -> str: | if width:<EOL><INDENT>return '<STR_LIT:\n>'.join(textwrap.wrap(text, width=width))<EOL><DEDENT>else:<EOL><INDENT>return text<EOL><DEDENT> | Word-wraps text.
Args:
text: text to process
width: width to word-wrap to (or 0 to skip word wrapping)
Returns:
wrapped text | f14622:m15 |
def docx_process_table(table: DOCX_TABLE_TYPE,<EOL>config: TextProcessingConfig) -> str: | def get_cell_text(cell_) -> str:<EOL><INDENT>cellparagraphs = [paragraph.text.strip()<EOL>for paragraph in cell_.paragraphs]<EOL>cellparagraphs = [x for x in cellparagraphs if x]<EOL>return '<STR_LIT>'.join(cellparagraphs)<EOL><DEDENT>ncols = <NUM_LIT:1><EOL>for row in table.rows:<EOL><INDENT>ncols = max(ncols, len(row... | Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows[]
.cells[]
.paragraphs[]
.text
That's the structure of a :class:`docx.table.Table` object, but also of our
homebrew creation, :class:`CustomDocxTable`.
Th... | f14622:m16 |
def docx_docx_iter_block_items(parent: DOCX_CONTAINER_TYPE)-> Iterator[DOCX_BLOCK_ITEM_TYPE]:<EOL> | if isinstance(parent, docx.document.Document):<EOL><INDENT>parent_elm = parent.element.body<EOL><DEDENT>elif isinstance(parent, docx.table._Cell):<EOL><INDENT>parent_elm = parent._tc<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for child in parent_elm.iterchildren():<EOL><INDENT>if isinstance... | Iterate through items of a DOCX file.
See https://github.com/python-openxml/python-docx/issues/40.
Yield each paragraph and table child within ``parent``, in document order.
Each returned value is an instance of either :class:`Table` or
:class:`Paragraph`. ``parent`` would most commonly be a reference to a main
:clas... | f14622:m17 |
def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE,<EOL>config: TextProcessingConfig) -> Iterator[str]:<EOL> | if in_order:<EOL><INDENT>for thing in docx_docx_iter_block_items(doc):<EOL><INDENT>if isinstance(thing, docx.text.paragraph.Paragraph):<EOL><INDENT>yield docx_process_simple_text(thing.text, config.width)<EOL><DEDENT>elif isinstance(thing, docx.table.Table):<EOL><INDENT>yield docx_process_table(thing, config)<EOL><DEDE... | Iterate through a DOCX file and yield text.
Args:
doc: DOCX document to process
config: :class:`TextProcessingConfig` control object
Yields:
pieces of text (paragraphs) | f14622:m18 |
def convert_docx_to_text(<EOL>filename: str = None, blob: bytes = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | if True:<EOL><INDENT>text = '<STR_LIT>'<EOL>with get_filelikeobject(filename, blob) as fp:<EOL><INDENT>for xml in gen_xml_files_from_docx(fp):<EOL><INDENT>text += docx_text_from_xml(xml, config)<EOL><DEDENT><DEDENT>return text<EOL><DEDENT> | Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to process
config: :class:`TextProcessingConfig` control object
Returns:
text contents
Notes:
- Old ``docx`` (https://pypi.python.org/pypi/python-docx) has been
... | f14622:m19 |
def convert_odt_to_text(filename: str = None,<EOL>blob: bytes = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | <EOL>with get_filelikeobject(filename, blob) as fp:<EOL><INDENT>z = zipfile.ZipFile(fp)<EOL>tree = ElementTree.fromstring(z.read('<STR_LIT>'))<EOL>textlist = [] <EOL>for element in tree.iter():<EOL><INDENT>if element.text:<EOL><INDENT>textlist.append(element.text.strip())<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT>'... | Converts an OpenOffice ODT file to text.
Pass either a filename or a binary object. | f14622:m20 |
def convert_html_to_text(<EOL>filename: str = None,<EOL>blob: bytes = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | with get_filelikeobject(filename, blob) as fp:<EOL><INDENT>soup = bs4.BeautifulSoup(fp)<EOL>return soup.get_text()<EOL><DEDENT> | Converts HTML to text. | f14622:m21 |
def convert_xml_to_text(filename: str = None,<EOL>blob: bytes = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | with get_filelikeobject(filename, blob) as fp:<EOL><INDENT>soup = bs4.BeautifulStoneSoup(fp)<EOL>return soup.get_text()<EOL><DEDENT> | Converts XML to text. | f14622:m22 |
def convert_rtf_to_text(filename: str = None,<EOL>blob: bytes = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | unrtf = tools['<STR_LIT>']<EOL>if unrtf: <EOL><INDENT>args = [unrtf, '<STR_LIT>', '<STR_LIT>']<EOL>if UNRTF_SUPPORTS_QUIET:<EOL><INDENT>args.append('<STR_LIT>')<EOL><DEDENT>if filename:<EOL><INDENT>args.append(filename)<EOL>return get_cmd_output(*args)<EOL><DEDENT>else:<EOL><INDENT>return get_cmd_output_from_stdin(blo... | Converts RTF to text. | f14622:m23 |
def availability_rtf() -> bool: | unrtf = tools['<STR_LIT>']<EOL>if unrtf:<EOL><INDENT>return True<EOL><DEDENT>elif pyth:<EOL><INDENT>log.warning("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Is an RTF processor available? | f14622:m24 |
def convert_doc_to_text(filename: str = None,<EOL>blob: bytes = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | antiword = tools['<STR_LIT>']<EOL>if antiword:<EOL><INDENT>if filename:<EOL><INDENT>return get_cmd_output(antiword, '<STR_LIT>', str(config.width), filename)<EOL><DEDENT>else:<EOL><INDENT>return get_cmd_output_from_stdin(blob, antiword, '<STR_LIT>',<EOL>str(config.width), '<STR_LIT:->')<EOL><DEDENT><DEDENT>else:<EOL><I... | Converts Microsoft Word DOC files to text. | f14622:m25 |
def availability_doc() -> bool: | antiword = tools['<STR_LIT>']<EOL>return bool(antiword)<EOL> | Is a DOC processor available? | f14622:m26 |
def convert_anything_to_text(<EOL>filename: str = None,<EOL>blob: bytes = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | strings = tools['<STR_LIT>'] or tools['<STR_LIT>']<EOL>if strings:<EOL><INDENT>if filename:<EOL><INDENT>return get_cmd_output(strings, filename)<EOL><DEDENT>else:<EOL><INDENT>return get_cmd_output_from_stdin(blob, strings)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Convert arbitrary files to text, using ``strings`` or ``strings2``.
(``strings`` is a standard Unix command to get text from any old rubbish.) | f14622:m27 |
def availability_anything() -> bool: | strings = tools['<STR_LIT>'] or tools['<STR_LIT>']<EOL>return bool(strings)<EOL> | Is a generic "something-to-text" processor available? | f14622:m28 |
def document_to_text(filename: str = None,<EOL>blob: bytes = None,<EOL>extension: str = None,<EOL>config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: | if not filename and not blob:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if filename and blob:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if blob and not extension:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if filename:<EOL><INDENT>stub, extension = os.path.splitext(filename)<EOL><DEDE... | Converts a document to text.
This function selects a processor based on the file extension (either from
the filename, or, in the case of a BLOB, the extension specified manually
via the ``extension`` parameter).
Pass either a filename or a binary object.
- Raises an exception for malformed arguments, missing files, ... | f14622:m29 |
def is_text_extractor_available(extension: str) -> bool: | if extension is not None:<EOL><INDENT>extension = extension.lower()<EOL><DEDENT>info = ext_map.get(extension)<EOL>if info is None:<EOL><INDENT>return False<EOL><DEDENT>availability = info[AVAILABILITY]<EOL>if type(availability) == bool:<EOL><INDENT>return availability<EOL><DEDENT>elif callable(availability):<EOL><INDEN... | Is a text extractor available for the specified extension? | f14622:m30 |
def require_text_extractor(extension: str) -> None: | if not is_text_extractor_available(extension):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(extension))<EOL><DEDENT> | Require that a text extractor is available for the specified extension,
or raise :exc:`ValueError`. | f14622:m31 |
def main() -> None: | logging.basicConfig(level=logging.DEBUG)<EOL>parser = argparse.ArgumentParser()<EOL>parser.add_argument("<STR_LIT>", nargs="<STR_LIT:?>", help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", nargs='<STR_LIT:*>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", actio... | Command-line processor. See ``--help`` for details. | f14622:m32 |
def __init__(self,<EOL>encoding: str = None,<EOL>width: int = DEFAULT_WIDTH,<EOL>min_col_width: int = DEFAULT_MIN_COL_WIDTH,<EOL>plain: bool = False,<EOL>docx_in_order: bool = True) -> None: | self.encoding = encoding<EOL>self.width = width<EOL>self.min_col_width = min_col_width<EOL>self.plain = plain<EOL>self.docx_in_order = docx_in_order<EOL> | Args:
encoding: optional text file encoding to try in addition to
:func:`sys.getdefaultencoding`.
width: overall word-wrapping width
min_col_width: minimum column width for tables
plain: as plain as possible (e.g. for natural language processing);
see :func:`docx_process_table`
docx_... | f14622:c0:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.