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[symbol]<EOL>return format % locals()<EOL><DEDENT>n format % dict(symbol=symbols[<NUM_LIT:0>], value=n)<EOL> | 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"``; see http://goo.gl/kTQMs
Returns:
the formatted number
Examples:
>>> bytes2human(0)
'0.0 B'
>>> bytes2human(0.9)
'0.0 B'
>>> bytes2human(1)
'1.0 B'
>>> bytes2human(1.9)
'1.0 B'
>>> bytes2human(1024)
'1.0 K'
>>> bytes2human(1048576)
'1.0 M'
>>> bytes2human(1099511627776127398123789121)
'909.5 Y'
>>> bytes2human(9856, symbols="customary")
'9.6 K'
>>> bytes2human(9856, symbols="customary_ext")
'9.6 kilo'
>>> bytes2human(9856, symbols="iec")
'9.6 Ki'
>>> bytes2human(9856, symbols="iec_ext")
'9.6 kibi'
>>> bytes2human(10000, "%(value).1f %(symbol)s/sec")
'9.8 K/sec'
>>> # precision can be adjusted by playing with %f operator
>>> bytes2human(10000, format="%(value).5f %(symbol)s")
'9.76562 K' | 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.strip()<EOL>ame, sset in SYMBOLS.items():<EOL>f letter in sset:<EOL><INDENT>break<EOL><DEDENT>f letter == '<STR_LIT:k>':<EOL><INDENT>sset = SYMBOLS['<STR_LIT>']<EOL>letter = letter.upper()<EOL><DEDENT>lse:<EOL><INDENT>raise ValueError("<STR_LIT>" % init)<EOL><DEDENT>x = {sset[<NUM_LIT:0>]: <NUM_LIT:1>}<EOL>, s in enumerate(sset[<NUM_LIT:1>:]):<EOL>refix[s] = <NUM_LIT:1> << (i + <NUM_LIT:1>) * <NUM_LIT:10><EOL>n int(num * prefix[letter])<EOL> | 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
>>> human2bytes('1 K')
1024
>>> human2bytes('1 M')
1048576
>>> human2bytes('1 Gi')
1073741824
>>> human2bytes('1 tera')
1099511627776
>>> human2bytes('0.5kilo')
512
>>> human2bytes('0.1 byte')
0
>>> human2bytes('1 k') # k is an alias for K
1024
>>> human2bytes('12 foo')
Traceback (most recent call last):
...
ValueError: can't interpret '12 foo' | 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, fail in re.findall(re_cmd_lex, s):<EOL>f word:<EOL><INDENT>pass <EOL><DEDENT>lif esc:<EOL><INDENT>word = esc[<NUM_LIT:1>]<EOL><DEDENT>lif white or pipe:<EOL><INDENT>if accu is not None:<EOL><INDENT>args.append(accu)<EOL><DEDENT>if pipe:<EOL><INDENT>args.append(pipe)<EOL><DEDENT>accu = None<EOL>continue<EOL><DEDENT>lif fail:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>lif qs:<EOL><INDENT>word = qs.replace('<STR_LIT>', '<STR_LIT:">').replace('<STR_LIT>', '<STR_LIT:\\>')<EOL>if platform == <NUM_LIT:0>:<EOL><INDENT>word = word.replace('<STR_LIT>', '<STR_LIT:">')<EOL><DEDENT><DEDENT>lse:<EOL><INDENT>word = qss <EOL><DEDENT>ccu = (accu or '<STR_LIT>') + word<EOL>cu is not None:<EOL>rgs.append(accu)<EOL>n args<EOL> | 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'`` = auto from current platform;
- ``1`` = POSIX;
- ``0`` = Windows/CMD
- (other values reserved) | 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/parsing-boolean-values-with-argparse
Specimen usage:
.. code-block:: python
parser.add_argument(
"--nice", type=str2bool, nargs='?',
const=True, # if --nice is present with no parameter
default=NICE, # if the argument is entirely absent
help="Activate nice mode.") | 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 coerce "to" values to; e.g. ``str``, ``int`` | 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><INDENT>return False<EOL><DEDENT>return h == storedhash<EOL> | 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):<EOL><INDENT>pass<EOL><DEDENT>if not isinstance(x, str):<EOL><INDENT>raise Exception("<STR_LIT>".format(x))<EOL><DEDENT>x = x.upper()<EOL>if x in ["<STR_LIT:Y>", "<STR_LIT>", "<STR_LIT:T>", "<STR_LIT>"]:<EOL><INDENT>return True<EOL><DEDENT>if x in ["<STR_LIT:N>", "<STR_LIT>", "<STR_LIT:F>", "<STR_LIT>"]:<EOL><INDENT>return False<EOL><DEDENT>raise Exception("<STR_LIT>".format(x))<EOL> | 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 special string
literals.
- SQLite uses this notation: https://sqlite.org/lang_expr.html
- Strip off the start and end and convert it to a byte array:
http://stackoverflow.com/questions/5649407 | 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://www.perlmonks.org/?node_id=775820 | 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 = M2Crypto.m2.rand_bytes(num_bytes) # NO!
randbytes = Crypto.Random.get_random_bytes(num_bytes) # NO!
Instead, do this:
.. code-block:: python
randbytes = os.urandom(num_bytes) # YES | 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_name)<EOL>results[full_name] = importlib.import_module(full_name)<EOL>if recursive and is_pkg:<EOL><INDENT>results.update(import_submodules(full_name))<EOL><DEDENT><DEDENT>return results<EOL> | 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.<EOL>_builtin_module(module):<EOL>eturn False<EOL>e, fallback to filetype matching heuristics.<EOL>olute path of the file defining this module.<EOL>e_filename = inspect.getfile(module)<EOL>-prefixed filetype of this path if any or the empty string otherwise.<EOL>e_filetype = os.path.splitext(module_filename)[<NUM_LIT:1>]<EOL>s module is only a C extension if this path's filetype is that of a<EOL>xtension specific to the current platform.<EOL>n module_filetype in EXTENSION_SUFFIXES<EOL> | 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 tested.
Returns:
bool: ``True`` only if this module is a C extension.
Examples:
.. code-block:: python
from cardinal_pythonlib.modules import is_c_extension
import os
import _elementtree as et
import numpy
import numpy.core.multiarray as numpy_multiarray
is_c_extension(os) # False
is_c_extension(numpy) # False
is_c_extension(et) # False on my system (Python 3.5.6). True in the original example.
is_c_extension(numpy_multiarray) # True | 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>_c_ext:<EOL>eturn True<EOL>_builtin_module(module):<EOL><INDENT>built-in, therefore we stop searching it<EOL><DEDENT>eturn False<EOL><INDENT>check any children, in a couple of ways<EOL><DEDENT>evel_module = seen[<NUM_LIT:0>]<EOL>ath = os.path.dirname(top_level_module.__file__)<EOL>urse using dir(). This picks up modules that are automatically<EOL>orted by our top-level model. But it won't pick up all submodules;<EOL><INDENT>e.g. for django.<EOL><DEDENT>andidate_name in dir(module):<EOL>andidate = getattr(module, candidate_name)<EOL><INDENT>noinspection PyBroadException<EOL><DEDENT>ry:<EOL><INDENT>if not inspect.ismodule(candidate):<EOL><INDENT>continue<EOL><DEDENT><DEDENT>xcept Exception:<EOL><INDENT>log.error("<STR_LIT>", candidate)<EOL>continue<EOL><DEDENT>f is_builtin_module(candidate):<EOL><INDENT>continue<EOL><DEDENT>andidate_fname = getattr(candidate, "<STR_LIT>")<EOL>f not include_external_imports:<EOL><INDENT>if os.path.commonpath([top_path, candidate_fname]) != top_path:<EOL><INDENT>log.debug("<STR_LIT>"<EOL>"<STR_LIT>", candidate)<EOL>continue<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
module imports?
seen: used internally for recursion (to deal with recursive modules);
should be ``None`` when called by users
Returns:
bool: ``True`` only if this module or one of its submodules is a C
extension.
Examples:
.. code-block:: python
import logging
from cardinal_pythonlib.modules import contains_c_extension
from cardinal_pythonlib.logs import main_only_quicksetup_rootlogger
import _elementtree as et
import os
import arrow
import alembic
import django
import numpy
import numpy.core.multiarray as numpy_multiarray
log = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG) # be verbose
main_only_quicksetup_rootlogger(level=logging.DEBUG)
contains_c_extension(os) # False
contains_c_extension(et) # False
contains_c_extension(numpy) # True -- different from is_c_extension()
contains_c_extension(numpy_multiarray) # True
contains_c_extension(arrow) # False
contains_c_extension(alembic) # False
contains_c_extension(alembic, include_external_imports=True) # True
# ... this example shows that Alembic imports hashlib, which can import
# _hashlib, which is a C extension; however, that doesn't stop us (for
# example) installing Alembic on a machine with no C compiler
contains_c_extension(django) | 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 executable manually.
Args:
executable: executable to find
env: environment to fetch the PATH variable from | 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: copy things that are not files too (as judged by
:func:`os.path.isfile`).
Raises:
ValueError: if no files are found and ``allow_nothing`` is not set | 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-block:: none
/dest/thing/a.txt
/dest/thing/b.txt
/dest/thing/somedir/c.txt | 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>shutil.copytree(srcdir, destdir)<EOL> | 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 creating:
.. code-block:: none
/dest/a.txt
/dest/b.txt
/dest/somedir/c.txt | 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/shutil-rmtree-fails-on-windows-with-access-is-denied | 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>yield os.path.abspath(os.path.join(dirpath, fname))<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | 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 filename | 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 IOError:<EOL><INDENT>pass<EOL><DEDENT>finally:<EOL><INDENT>if file_object:<EOL><INDENT>file_object.close()<EOL><DEDENT><DEDENT><DEDENT>return exists, locked<EOL> | 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 are:
=========== ======================= =====================================
Signal Meaning Comment
=========== ======================= =====================================
SIGABRT abnormal termination
SIGFPE floating-point error
SIGILL illegal instruction
SIGINT CTRL+C signal -- trapped here
SIGSEGV illegal storage access
SIGTERM termination request -- trapped here
SIGBREAK CTRL+BREAK -- trapped here under Windows
=========== ======================= =====================================
In Linux, you also find:
=========== =============================
Signal Meaning
=========== =============================
SIGBUS bus error / unaligned access
=========== =============================
To ignore, can do:
.. code-block:: python
signal.signal(signal.SIGINT, signal.SIG_IGN) # SIG_IGN = "ignore me"
or pass a specified handler, as in the code here. | 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. If either is PIPE, you'll need to deal with the
output.
stderr: As above. You can use stderr=STDOUT to route stderr to the same
place as stdout.
Returns:
The process object (which is also stored in :data:`processes`). | 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 retcode == <NUM_LIT:0>:<EOL><INDENT>log.info("<STR_LIT>", i, n)<EOL><DEDENT>if retcode != <NUM_LIT:0>:<EOL><INDENT>log.critical(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>i, n, retcode, proc_args_list[i])<EOL>if die_on_failure:<EOL><INDENT>log.critical("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>fail() <EOL><DEDENT><DEDENT><DEDENT>except TimeoutExpired:<EOL><INDENT>something_running = True<EOL><DEDENT><DEDENT><DEDENT>processes.clear()<EOL>proc_args_list.clear()<EOL> | 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 a full quit instantly (or potentially for ages).
If ``timeout_sec`` is something else, each process is tried for that time;
if it quits within that time, well and good (successful quit -> continue
waiting for the others; failure -> kill everything, if ``die_on_failure``);
if it doesn't, we try the next. That is much more responsive. | 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_encoding: str = None,<EOL>suppress_decoding_errors: bool = True,<EOL>sleep_time_s: float = <NUM_LIT:0.1>) -> None: | <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 stderr<EOL>t_queue = Queue()<EOL>nspection PyTypeChecker<EOL>t_reader = AsynchronousFileReader(<EOL>d=p.stdout,<EOL>ueue=stdout_queue,<EOL>ncoding=stdout_encoding,<EOL>ine_terminators=line_terminators,<EOL>mdargs=args,<EOL>uppress_decoding_errors=suppress_decoding_errors<EOL>t_reader.start()<EOL>r_queue = Queue()<EOL>nspection PyTypeChecker<EOL>r_reader = AsynchronousFileReader(<EOL>d=p.stderr,<EOL>ueue=stderr_queue,<EOL>ncoding=stdout_encoding, <EOL>ine_terminators=line_terminators,<EOL>mdargs=args,<EOL>uppress_decoding_errors=suppress_decoding_errors<EOL>r_reader.start()<EOL>not stdout_reader.eof() or not stderr_reader.eof():<EOL>ines_with_source = [] <EOL>hile not stdout_queue.empty():<EOL>lines_with_source.append((SOURCE_STDOUT, stdout_queue.get()))<EOL>hile not stderr_queue.empty():<EOL>lines_with_source.append((SOURCE_STDERR, stderr_queue.get()))<EOL>or src, line in lines_with_source:<EOL>if src is SOURCE_STDOUT and print_stdout:<EOL>print(line, end="<STR_LIT>") <EOL>if src is SOURCE_STDERR and print_stderr:<EOL>print(line, end="<STR_LIT>") <EOL>for challsrc, challenge, response in source_challenge_response:<EOL>if challsrc != src:<EOL>continue<EOL>if challenge in line:<EOL>if response is TERMINATE_SUBPROCESS:<EOL>log.warning("<STR_LIT>"<EOL>"<STR_LIT>", args, challenge)<EOL>p.kill()<EOL>return<EOL>else:<EOL>p.stdin.write(response.encode(stdin_encoding))<EOL>p.stdin.flush()<EOL>if print_stdin:<EOL>print(response, end="<STR_LIT>")<EOL>Sleep a bit before asking the readers again.<EOL>leep(sleep_time_s)<EOL>t_reader.join()<EOL>r_reader.join()<EOL>out.close()<EOL>err.close()<EOL> | 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,
challenge, response)``; see below
line_terminators: valid line terminators
print_stdout:
print_stderr:
print_stdin:
stdin_encoding:
stdout_encoding:
suppress_decoding_errors: trap any ``UnicodeDecodeError``?
sleep_time_s:
The ``(challsrc, challenge, response)`` tuples have this meaning:
- ``challsrc``: where is the challenge coming from? Must be one of the
objects :data:`SOURCE_STDOUT` or :data:`SOURCE_STDERR`;
- ``challenge``: text of challenge
- ``response``: text of response (send to the subcommand's ``stdin``).
Example (modified from :class:`CorruptedZipReader`):
.. code-block:: python
from cardinal_pythonlib.subproc import *
SOURCE_FILENAME = "corrupt.zip"
TMP_DIR = "/tmp"
OUTPUT_FILENAME = "rescued.zip"
cmdargs = [
"zip", # Linux zip tool
"-FF", # or "--fixfix": "fix very broken things"
SOURCE_FILENAME, # input file
"--temp-path", TMP_DIR, # temporary storage path
"--out", OUTPUT_FILENAME # output file
]
# We would like to be able to say "y" automatically to
# "Is this a single-disk archive? (y/n):"
# The source code (api.c, zip.c, zipfile.c), from
# ftp://ftp.info-zip.org/pub/infozip/src/ , suggests that "-q"
# should do this (internally "-q" sets "noisy = 0") - but in
# practice it doesn't work. This is a critical switch.
# Therefore we will do something very ugly, and send raw text via
# stdin.
ZIP_PROMPTS_RESPONSES = [
(SOURCE_STDOUT, "Is this a single-disk archive? (y/n): ", "y\n"),
(SOURCE_STDOUT, " or ENTER (try reading this split again): ", "q\n"),
(SOURCE_STDERR,
"zip: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) "
"&& old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && "
"prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) "
"== 0)' failed.", TERMINATE_SUBPROCESS),
]
ZIP_STDOUT_TERMINATORS = ["\n", "): "]
mimic_user_input(cmdargs,
source_challenge_response=ZIP_PROMPTS_RESPONSES,
line_terminators=ZIP_STDOUT_TERMINATORS,
print_stdout=show_zip_output,
print_stdin=show_zip_output) | 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_errors<EOL> | 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 ``UnicodeDecodeError``? | 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)<EOL>if self._suppress_decoding_errors:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>if not c:<EOL><INDENT>return<EOL><DEDENT>buf += c<EOL>for t in line_terminators:<EOL><INDENT>try:<EOL><INDENT>t_idx = buf.index(t) + len(t) <EOL>fragment = buf[:t_idx]<EOL>buf = buf[t_idx:]<EOL>queue.put(fragment)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT> | 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.decode(sys.getdefaultencoding())<EOL>lines = text.split()<EOL>if len(lines) < <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>version_str = lines[<NUM_LIT:0>]<EOL>unrtf_version = Version(version_str)<EOL>return unrtf_version >= required_unrtf_version<EOL> | 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.done:<EOL><INDENT>break<EOL><DEDENT><DEDENT>guess = detector.result<EOL>if '<STR_LIT>' not in guess:<EOL><INDENT>log.warning("<STR_LIT>")<EOL>return None<EOL><DEDENT>return guess['<STR_LIT>']<EOL> | 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:<EOL><INDENT>return binary_contents.decode(sysdef)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if chardet:<EOL><INDENT>guess = chardet.detect(binary_contents)<EOL>if guess['<STR_LIT>']:<EOL><INDENT>return binary_contents.decode(guess['<STR_LIT>'])<EOL><DEDENT><DEDENT>raise ValueError("<STR_LIT>".format(<EOL>"<STR_LIT>".format(repr(filename)) if filename else "<STR_LIT>"))<EOL> | 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_filelikeobject(filename, blob) as fp:<EOL><INDENT>rsrcmgr = pdfminer.pdfinterp.PDFResourceManager()<EOL>retstr = StringIO()<EOL>codec = ENCODING<EOL>laparams = pdfminer.layout.LAParams()<EOL>device = pdfminer.converter.TextConverter(<EOL>rsrcmgr, retstr, codec=codec, laparams=laparams)<EOL>interpreter = pdfminer.pdfinterp.PDFPageInterpreter(rsrcmgr,<EOL>device)<EOL>password = "<STR_LIT>"<EOL>maxpages = <NUM_LIT:0><EOL>caching = True<EOL>pagenos = set()<EOL>for page in pdfminer.pdfpage.PDFPage.get_pages(<EOL>fp, pagenos, maxpages=maxpages, password=password,<EOL>caching=caching, check_extractable=True):<EOL><INDENT>interpreter.process_page(page)<EOL><DEDENT>text = retstr.getvalue().decode(ENCODING)<EOL><DEDENT>return text<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | 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_FILE_REGEX.match(filename):<EOL><INDENT>yield z.read(filename).decode("<STR_LIT:utf8>")<EOL><DEDENT><DEDENT><DEDENT>except zipfile.BadZipFile:<EOL><INDENT>raise zipfile.BadZipFile("<STR_LIT>")<EOL><DEDENT> | 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>'<EOL><DEDENT>if node.tag == DOCX_TABLE:<EOL><INDENT>text += '<STR_LIT>' + docx_table_from_xml_node(node, level, config)<EOL><DEDENT>else:<EOL><INDENT>for child in node:<EOL><INDENT>text += docx_text_from_xml_node(child, level + <NUM_LIT:1>, config)<EOL><DEDENT><DEDENT>return text<EOL> | 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><INDENT>text = docx_text_from_xml_node(para_node, level, config)<EOL>if text:<EOL><INDENT>table.add_paragraph(text)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return docx_process_table(table, config)<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.cells))<EOL><DEDENT>pt = prettytable.PrettyTable(<EOL>field_names=list(range(ncols)),<EOL>encoding=ENCODING,<EOL>header=False,<EOL>border=True,<EOL>hrules=prettytable.ALL,<EOL>vrules=prettytable.NONE if config.plain else prettytable.ALL,<EOL>)<EOL>pt.align = '<STR_LIT:l>'<EOL>pt.valign = '<STR_LIT:t>'<EOL>pt.max_width = max(config.width // ncols, config.min_col_width)<EOL>if config.plain:<EOL><INDENT>for row in table.rows:<EOL><INDENT>for i, cell in enumerate(row.cells):<EOL><INDENT>n_before = i<EOL>n_after = ncols - i - <NUM_LIT:1><EOL>ptrow = (<EOL>['<STR_LIT>'] * n_before +<EOL>[get_cell_text(cell)] +<EOL>['<STR_LIT>'] * n_after<EOL>)<EOL>assert(len(ptrow) == ncols)<EOL>pt.add_row(ptrow)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for row in table.rows:<EOL><INDENT>ptrow = [] <EOL>for cell in row.cells:<EOL><INDENT>ptrow.append(get_cell_text(cell))<EOL><DEDENT>ptrow += ['<STR_LIT>'] * (ncols - len(ptrow)) <EOL>assert (len(ptrow) == ncols)<EOL>pt.add_row(ptrow)<EOL><DEDENT><DEDENT>return pt.get_string()<EOL> | 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`.
The ``plain`` option optimizes for natural language processing, by:
- removing vertical lines:
.. code-block:: none
+-------------+-------------+
| AAA AAA | BBB BBB |
| AAA AAA | BBB BBB |
+-------------+-------------+
becomes
.. code-block:: none
-----------------------------
AAA AAA BBB BBB
AAA AAA BBB BBB
-----------------------------
- and offsetting cells:
.. code-block:: none
AAA AAA BBB BBB CCC CCC
AAA AAA BBB BBB CCC CCC
becomes
.. code-block:: none
AAA AAA
AAA AAA
BBB BBB
BBB BBB
CCC CCC
CCC CCC
- Note also that the grids in DOCX files can have varying number of cells
per row, e.g.
.. code-block:: none
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 1 | 2 |
+---+---+ | 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(child, docx.oxml.text.paragraph.CT_P):<EOL><INDENT>yield docx.text.paragraph.Paragraph(child, parent)<EOL><DEDENT>elif isinstance(child, docx.oxml.table.CT_Tbl):<EOL><INDENT>yield docx.table.Table(child, parent)<EOL><DEDENT><DEDENT> | 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
:class:`Document` object, but also works for a :class:`_Cell` object, which
itself can contain paragraphs and tables.
NOTE: uses internals of the ``python-docx`` (``docx``) library; subject to
change; this version works with ``docx==0.8.5``. | 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><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for paragraph in doc.paragraphs:<EOL><INDENT>yield docx_process_simple_text(paragraph.text, config.width)<EOL><DEDENT>for table in doc.tables:<EOL><INDENT>yield docx_process_table(table, config)<EOL><DEDENT><DEDENT> | 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
superseded (see https://github.com/mikemaccana/python-docx).
- ``docx.opendocx(file)`` uses :class:`zipfile.ZipFile`, which can take
either a filename or a file-like object
(https://docs.python.org/2/library/zipfile.html).
- Method was:
.. code-block:: python
with get_filelikeobject(filename, blob) as fp:
document = docx.opendocx(fp)
paratextlist = docx.getdocumenttext(document)
return '\n\n'.join(paratextlist)
- Newer ``docx`` is python-docx
- https://pypi.python.org/pypi/python-docx
- https://python-docx.readthedocs.org/en/latest/
- http://stackoverflow.com/questions/25228106
However, it uses ``lxml``, which has C dependencies, so it doesn't always
install properly on e.g. bare Windows machines.
PERFORMANCE of my method:
- nice table formatting
- but tables grouped at end, not in sensible places
- can iterate via ``doc.paragraphs`` and ``doc.tables`` but not in
true document order, it seems
- others have noted this too:
- https://github.com/python-openxml/python-docx/issues/40
- https://github.com/deanmalmgren/textract/pull/92
- ``docx2txt`` is at https://pypi.python.org/pypi/docx2txt/0.6; this is
pure Python. Its command-line function appears to be for Python 2 only
(2016-04-21: crashes under Python 3; is due to an encoding bug). However,
it seems fine as a library. It doesn't handle in-memory blobs properly,
though, so we need to extend it.
PERFORMANCE OF ITS ``process()`` function:
- all text comes out
- table text is in a sensible place
- table formatting is lost.
- Other manual methods (not yet implemented):
http://etienned.github.io/posts/extract-text-from-word-docx-simply/.
Looks like it won't deal with header stuff (etc.) that ``docx2txt``
handles.
- Upshot: we need a DIY version.
- See also this "compile lots of techniques" libraries, which has C
dependencies: http://textract.readthedocs.org/en/latest/ | 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>'.join(textlist)<EOL> | 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(blob, *args)<EOL><DEDENT><DEDENT>elif pyth: <EOL><INDENT>with get_filelikeobject(filename, blob) as fp:<EOL><INDENT>doc = pyth.plugins.rtf15.reader.Rtf15Reader.read(fp)<EOL><DEDENT>return (<EOL>pyth.plugins.plaintext.writer.PlaintextWriter.write(doc).getvalue()<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | 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><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | 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><DEDENT>else:<EOL><INDENT>if extension[<NUM_LIT:0>] != "<STR_LIT:.>":<EOL><INDENT>extension = "<STR_LIT:.>" + extension<EOL><DEDENT><DEDENT>extension = extension.lower()<EOL>log.debug(<EOL>"<STR_LIT>".format(<EOL>filename,<EOL>type(blob),<EOL>len(blob) if blob is not None else None,<EOL>extension))<EOL>if filename and not os.path.isfile(filename):<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>filename))<EOL><DEDENT>info = ext_map.get(extension)<EOL>if info is None:<EOL><INDENT>log.warning("<STR_LIT>", extension)<EOL>info = ext_map[None]<EOL><DEDENT>func = info[CONVERTER]<EOL>return func(filename, blob, config)<EOL> | 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, bad
filetypes, etc.
- Returns a string if the file was processed (potentially an empty string). | 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><INDENT>return availability()<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(extension))<EOL><DEDENT> | 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>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int, default=DEFAULT_WIDTH,<EOL>help="<STR_LIT>".format(DEFAULT_WIDTH))<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int, default=DEFAULT_MIN_COL_WIDTH,<EOL>help="<STR_LIT>".format(<EOL>DEFAULT_MIN_COL_WIDTH))<EOL>args = parser.parse_args()<EOL>if args.availability:<EOL><INDENT>for ext in args.availability:<EOL><INDENT>if ext.lower() == '<STR_LIT:none>':<EOL><INDENT>ext = None<EOL><DEDENT>available = is_text_extractor_available(ext)<EOL>print("<STR_LIT>".format(ext,<EOL>available))<EOL><DEDENT>return<EOL><DEDENT>if not args.inputfile:<EOL><INDENT>parser.print_help(sys.stderr)<EOL>return<EOL><DEDENT>config = TextProcessingConfig(<EOL>width=args.width,<EOL>min_col_width=args.min_col_width,<EOL>plain=args.plain,<EOL>)<EOL>result = document_to_text(filename=args.inputfile, config=config)<EOL>if result is None:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>print(result)<EOL><DEDENT> | 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_in_order: for DOCX files: if ``True``, process paragraphs and
tables in the order they occur; if ``False``, process all
paragraphs followed by all tables | f14622:c0:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.