text
stringlengths
81
112k
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 def import_submodul...
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 impo...
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 packa...
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 ...
If ``executable`` is not found by :func:`shutil.which`, raise :exc:`FileNotFoundError`. def require_executable(executable: str) -> None: """ If ``executable`` is not found by :func:`shutil.which`, raise :exc:`FileNotFoundError`. """ if shutil.which(executable): return errmsg = "Miss...
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. def mkdir_p(path: str) -> None: """ Makes a directory, and any intermediate (parent) directories if required. ...
Context manager: changes directory and preserves the original on exit. Example: .. code-block:: python with pushd(new_directory): # do things def pushd(directory: str) -> None: """ Context manager: changes directory and preserves the original on exit. Example: .. code-b...
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" def preserve_cwd(func: Ca...
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 fo...
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"...
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("/sourc...
Deletes all files whose filename matches the glob ``pattern`` (via :func:`glob.glob`). def rmglob(pattern: str) -> None: """ Deletes all files whose filename matches the glob ``pattern`` (via :func:`glob.glob`). """ for f in glob.glob(pattern): os.remove(f)
Deletes all files in ``path`` matching ``pattern`` (via :func:`fnmatch.fnmatch`). def purge(path: str, pattern: str) -> None: """ Deletes all files in ``path`` matching ``pattern`` (via :func:`fnmatch.fnmatch`). """ for f in find(pattern, path): log.info("Deleting {}", f) os.rem...
Delete files within ``directory`` whose filename *exactly* matches one of ``filenames``. def delete_files_within_dir(directory: str, filenames: List[str]) -> None: """ Delete files within ``directory`` whose filename *exactly* matches one of ``filenames``. """ for dirpath, dirnames, fnames in o...
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://stackove...
Deletes a directory tree. def rmtree(directory: str) -> None: """ Deletes a directory tree. """ log.debug("Deleting directory {!r}", directory) shutil.rmtree(directory, onerror=shutil_rmtree_onerror)
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 def chown_r(path: str, user: str, group: str) -> None: """ Performs a recursive ``chown``. Args: path: pat...
Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR`` def chmod_r(root: str, permission: int) -> None: """ Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR`` """ os.chmod(root,...
Finds files in ``path`` whose filenames match ``pattern`` (via :func:`fnmatch.fnmatch`). def find(pattern: str, path: str) -> List[str]: """ Finds files in ``path`` whose filenames match ``pattern`` (via :func:`fnmatch.fnmatch`). """ result = [] for root, dirs, files in os.walk(path): ...
Finds first file in ``path`` whose filename matches ``pattern`` (via :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`. def find_first(pattern: str, path: str) -> str: """ Finds first file in ``path`` whose filename matches ``pattern`` (via :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`. ...
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? ...
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/. def exists_...
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. def relative_filename_within_dir(filename: str, directory: str) -> str: """ Starting with a (typically...
Gets errors from HTTP response def _get_errors(self): """ Gets errors from HTTP response """ errors = self.json.get('data').get('failures') if errors: logger.error(errors) return errors
Generates the final page sequence from the starting number of sheets. def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: """ Generates the final page sequence from the starting number of sheets. """ n_pages = calc_n_virtual_pages(n_sheets) assert n_pages % 4 == 0 half_n_page...
Ensures that the external tool is available. Asserts upon failure. def require(executable: str, explanation: str = "") -> None: """ Ensures that the external tool is available. Asserts upon failure. """ assert shutil.which(executable), "Need {!r} on the PATH.{}".format( executable, "\n"...
Run an external command +/- return the results. Returns a ``(stdout, stderr)`` tuple (both are blank strings if the output wasn't wanted). def run(args: List[str], get_output: bool = False, encoding: str = sys.getdefaultencoding()) -> Tuple[str, str]: """ Run an external command +/- ret...
How many pages are in a PDF? def get_page_count(filename: str) -> int: """ How many pages are in a PDF? """ log.debug("Getting page count for {!r}", filename) require(PDFTK, HELP_MISSING_PDFTK) stdout, _ = run([PDFTK, filename, "dump_data"], get_output=True) regex = re.compile(r"^NumberOfPa...
NOT USED. Makes a blank single-page PDF, using ImageMagick's ``convert``. def make_blank_pdf(filename: str, paper: str = "A4") -> None: """ NOT USED. Makes a blank single-page PDF, using ImageMagick's ``convert``. """ # https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf...
Slice each page of the original, to convert to "one real page per PDF page". Return the output filename. def slice_pdf(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int) -> str: """ Slice each page of the original, to convert to "one real page per PDF page". Ret...
Takes a PDF (e.g. A4) and makes a 2x1 booklet (e.g. 2xA5 per A4). The booklet can be folded like a book and the final pages will be in order. Returns the output filename. def booklet_nup_pdf(input_filename: str, output_filename: str, latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> str: ...
Rotates even-numbered pages 180 degrees. Returns the output filename. def rotate_even_pages_180(input_filename: str, output_filename: str) -> str: """ Rotates even-numbered pages 180 degrees. Returns the output filename. """ log.info("Rotating even-numbered pages 180 degrees for long-edge " ...
Runs a chain of tasks to convert a PDF to a useful booklet PDF. def convert_to_foldable(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int, overwrite: bool = False, longedge...
Command-line processor. See ``--help`` for details. def main() -> None: """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser....
Asks MySQL for its variables and status. Args: mysql: ``mysql`` executable filename host: host name port: TCP/IP port number user: username Returns: dictionary of MySQL variables/values def get_mysql_vars(mysql: str, host: str, por...
Converts a value in bytes (in string format) to megabytes. def val_mb(valstr: Union[int, str]) -> str: """ Converts a value in bytes (in string format) to megabytes. """ try: return "{:.3f}".format(int(valstr) / (1024 * 1024)) except (TypeError, ValueError): return '?'
Adds a row to ``table`` for ``varname``, in megabytes. def add_var_mb(table: PrettyTable, vardict: Dict[str, str], varname: str) -> None: """ Adds a row to ``table`` for ``varname``, in megabytes. """ valstr = vardict.get(varname, None) table.add_row([varname, val_mb(v...
Command-line processor. See ``--help`` for details. def main(): """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument( "--mysql", default="mysql", help="MySQL progra...
For "hits": prints either the ``.zip`` filename, or the ``.zip`` filename and the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file show_inner_file: if ``True``, show both; if ``False``, show just the ``.zip`` filen...
Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file line: the line from the inner file show_inner_file: if ``True``, show both filenames; if ``...
Implement a "grep within an OpenXML file" for a single OpenXML file, which is by definition a ``.zip`` file. Args: zipfilename: name of the OpenXML (zip) file regex: regular expression to match invert_match: find files that do NOT match, instead of ones that do? files_with_match...
Command-line handler for the ``grep_in_openxml`` tool. Use the ``--help`` option for help. def main() -> None: """ Command-line handler for the ``grep_in_openxml`` tool. Use the ``--help`` option for help. """ parser = ArgumentParser( formatter_class=RawDescriptionHelpFormatter, ...
Takes a set of drug event start times (one or more per patient), plus a fixed time that each event is presumed to last for, and returns an :class:`IntervalList` for each patient representing the set of events (which may overlap, in which case they will be amalgamated). Args: drug_events_d...
Args: drug_events_df: pandas :class:`DataFrame` containing the event data, with columns named according to ``patient_colname``, ``event_datetime_colname`` event_lasts_for_timedelta: when an event occurs, how long is it assumed to last for? For exampl...
Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :param xpath: T...
Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: list of ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpa...
Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ def find_element_by_xpath(self, xpath): """ Finds an element...
Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ def find_elements_by_xpath(self, xpath): """ Fin...
Parameters: .. code-block:: json { "param1": "value1", "param2": "value2", "param3": { "param31": "value31" } } def http_response_body_should_be_this_json(context): """ Parameters: .. ...
Queue a job in Rhumba def queue(self, queue, message, params={}, uids=[]): """ Queue a job in Rhumba """ d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': message, 'params': params } ser = json.dumps(d) ...
Returns a dict of cluster nodes and their status information def clusterStatus(self): """ Returns a dict of cluster nodes and their status information """ servers = yield self.getClusterServers() d = { 'workers': {}, 'crons': {}, 'queues': {}...
Returns the extra HTML that needs to be injected into the ``<head>`` section for a Deform form to work properly. def get_head_form_html(req: "Request", forms: List[Form]) -> str: """ Returns the extra HTML that needs to be injected into the ``<head>`` section for a Deform form to work properly. """...
Use as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, and whether it accepted or rejected the value). def debug_validator(validato...
Starting with a Deform :class:`Field`, yield the field itself and any children. def gen_fields(field: Field) -> Generator[Field, None, None]: """ Starting with a Deform :class:`Field`, yield the field itself and any children. """ yield field for c in field.children: for f in gen_fie...
Validates the form. Args: controls: an iterable of ``(key, value)`` tuples subcontrol: Returns: a Colander ``appstruct`` Raises: ValidationFailure: on failure def validate(self, controls: Iterable[Tuple[str, str]], ...
**uid**: :code:`{levelcode}` def save(self, *args, **kwargs): """ **uid**: :code:`{levelcode}` """ self.slug = slugify(self.name) self.uid = self.slug super(DivisionLevel, self).save(*args, **kwargs)
Print stats with a filter or exclude filenames, sort index and limit. :param list fnames: cProfile standard files to process. :param list filter_fnames: Relative paths to filter and show them. :param list exclude_fnames: Relative paths to avoid show them. :param str sort: Standard `pstats` key of value ...
Print list of pstats dict formatted :param list pstats: pstats dicts to print :param str format: String.format style to show fields with keys: ncalls, tottime, tt_percall, cumtime, ct_percall, file, lineno, method rcalls, calls :return: Directly print of result formatted and return True def...
Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics def merge_metrics(self): """ Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics """ self.metrics.extend(self._metrics.values()) ...
:param name: Name of the attribute :type name: string :param value: Value of the attribute :type value: string def add_attribute(self, name, value): """ :param name: Name of the attribute :type name: string :param value: Value of the attri...
:param name: Name of the tag :type name: string :param value: Value of the tag :type value: string def add_tag(self, name, value): """ :param name: Name of the tag :type name: string :param value: Value of the tag :type value: ...
:param metricId: Metric FQN :type metricId: string :param timestamp: Timestamp for the sample :type timestamp: int :param value: Value of the sample :type value: float :param metricType: Metric Type :type metricType: string ...
Pair each element with its neighbors. Arguments --------- iterable : iterable Returns ------- The generator produces a tuple containing a pairing of each element with its neighbor. def pairwise(iterable): """Pair each element with its neighbors. Arguments --------- iterab...
Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple of lists with the first list containin...
Return the powerset. Arguments --------- iterable : iterable reverse : boolean Indicates whether the powerset should be returned descending by size Returns ------- A generator producing each element of the powerset. def powerset(iterable, *, reverse=False): ...
Collect data into a multi-map. Arguments ---------- key : function A function that accepts an element retrieved from the iterable and returns the key to be used in the multi-map iterable : iterable default_dict : boolean Indicate...
Split the iterable. Arguments ---------- pred : function A function that accepts an element retrieved from the iterable and returns a boolean indicating if it is the element on which to split iterable : iterable trailing : boolean Indi...
Collect data into chunks. Arguments --------- iterable : iterable length : integer Maximum size of each chunk to return Returns ------- The generator produces a tuple of elements whose size is at least one but no more than *length*. If the number of elements in th...
Evenly divide elements. Arguments --------- iterable : iterable n : integer The number of buckets in which to divide the elements Returns ------- The generator produces *n* tuples, each containing a number of elements where the number is calculated to be evenly di...
Evenly divide a count. Arguments --------- count : integer The number to be evenly divided n : integer The number of buckets in which to divide the number Returns ------- A list of integers indicating what size each bucket should be for an even distribution ...
Display the AST represented by the cursor def dump(cursor): """ Display the AST represented by the cursor """ def node_children(node): return list(node.get_children()) def print_node(node): text = node.spelling or node.displayname kind = str(node.kind).split('.')[1] re...
Converts something to a :class:`pendulum.DateTime`. Args: x: something that may be coercible to a datetime assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.DateTime`, or ``None``. Raises: pendulum.parsing.ex...
Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.Date`, or ``None``. Raises: pendulum.parsing.exceptions.Par...
Used, for example, where a database backend insists on datetime.datetime. Compare code in :meth:`pendulum.datetime.DateTime.int_timestamp`. def pendulum_to_datetime(x: DateTime) -> datetime.datetime: """ Used, for example, where a database backend insists on datetime.datetime. Compare code in :meth:`...
Converts a Pendulum ``DateTime`` (which will have timezone information) to a ``datetime.datetime`` that (a) has no timezone information, and (b) is in UTC. Example: .. code-block:: python import pendulum from cardinal_pythonlib.datetimefunc import * in_moscow = pendulum.parse(...
Takes a :class:`pendulum.Date` and returns a :class:`datetime.date`. Used, for example, where a database backend insists on :class:`datetime.date`. def pendulum_date_to_datetime_date(x: Date) -> datetime.date: """ Takes a :class:`pendulum.Date` and returns a :class:`datetime.date`. Used, for exampl...
Takes a :class:`pendulum.Time` and returns a :class:`datetime.time`. Used, for example, where a database backend insists on :class:`datetime.time`. def pendulum_time_to_datetime_time(x: Time) -> datetime.time: """ Takes a :class:`pendulum.Time` and returns a :class:`datetime.time`. Used, for exampl...
Format a datetime with a ``strftime`` format specification string, or return ``default`` if the input is ``None``. def format_datetime(d: PotentialDatetimeType, fmt: str, default: str = None) -> Optional[str]: """ Format a datetime with a ``strftime`` format specific...
Convert a ``datetime.timedelta`` object or a regular number to a custom- formatted string, just like the ``strftime()`` method does for ``datetime.datetime`` objects. The ``fmt`` argument allows custom formatting to be specified. Fields can include ``seconds``, ``minutes``, ``hours``, ``days``, and ``w...
Convert date/time with timezone to UTC (with UTC timezone). def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime: """ Convert date/time with timezone to UTC (with UTC timezone). """ dt = coerce_to_pendulum(dt) tz = get_tz_utc() return dt.in_tz(tz)
Convert date/time with timezone to local timezone. def convert_datetime_to_local(dt: PotentialDatetimeType) -> DateTime: """ Convert date/time with timezone to local timezone. """ dt = coerce_to_pendulum(dt) tz = get_tz_local() return dt.in_tz(tz)
Calculate the time between two dates/times expressed as strings. Args: start: start date/time end: end date/time default: string value to return in case either of the inputs is ``None`` Returns: a string that is one of .. code-block: 'hh:mm' ...
Age (in whole years) at a particular date, or ``default``. Args: dob: date of birth when: date/time at which to calculate age default: value to return if either input is ``None`` Returns: age in whole years (rounded down), or ``default`` def get_age(dob: PotentialDatetimeType,...
Change the day to the first of the month. def truncate_date_to_first_of_month( dt: Optional[DateLikeType]) -> Optional[DateLikeType]: """ Change the day to the first of the month. """ if dt is None: return None return dt.replace(day=1)
Get the UTC time now, but with no timezone information, in :class:`datetime.datetime` format. def get_now_utc_notz_datetime() -> datetime.datetime: """ Get the UTC time now, but with no timezone information, in :class:`datetime.datetime` format. """ now = datetime.datetime.utcnow() return n...
Ensure an object is a :class:`datetime.datetime`, or coerce to one, or raise :exc:`ValueError` or :exc:`OverflowError` (as per http://dateutil.readthedocs.org/en/latest/parser.html). def coerce_to_datetime(x: Any) -> Optional[datetime.datetime]: """ Ensure an object is a :class:`datetime.datetime`, or ...
Do http requests from context. :param context: request context. def request_from_context(context): """ Do http requests from context. :param context: request context. """ new_context = copy.deepcopy(context) assert new_context.method in ALLOWED_METHODS new_context.url_path = generate...
Set default values to **self.fields_to_clear**. In addition, it is possible to pass extra fields to clear. :param args: extra fields to clear. def clear(self, *args): """ Set default values to **self.fields_to_clear**. In addition, it is possible to pass extra fields to clear. :param ...
A string that will be automatically included at the beginning of the url generated for doing each http request. :param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port) def host(self, value): """ A string that will be automatically included at the beginning...
Set cookie. :param value: def cookie(self, value): """ Set cookie. :param value: """ if value and not value.is_empty(): self._cookie = value else: self._cookie = Cookie()
Default: "http://127.0.0.1:80" A string that will be automatically included at the beginning of the url generated for doing each http request. def set_default_host(cls, value): """ Default: "http://127.0.0.1:80" A string that will be automatically included at the beginning of the url ...
Default: None (no proxy) A string that will be used to tell each request must be sent through this proxy server. Use the scheme://hostname:port form. If you need to use a proxy, you can configure individual requests with the proxies argument to any request method. def set_default_proxy...
Method to do http requests. :param method: :param url_path: :param headers: :param body_params: :param query_params: :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ...
Login abstract method with default implementation. :param kwargs: parameters :return: SdkResponse def login(self, **kwargs): """ Login abstract method with default implementation. :param kwargs: parameters :return: SdkResponse """ assert self.LOGIN_URL_...
Calculates an NHS number check digit. Args: ninedigits: string or list Returns: check digit Method: 1. Multiply each of the first nine digits by the corresponding digit weighting (see :const:`NHS_DIGIT_WEIGHTINGS`). 2. Sum the results. 3. Take remainder after division ...
Validates an integer as an NHS number. Args: n: NHS number Returns: valid? Checksum details are at http://www.datadictionary.nhs.uk/version2/data_dictionary/data_field_notes/n/nhs_number_de.asp def is_valid_nhs_number(n: int) -> bool: """ Validates an integer as an NHS nu...
Returns a random valid NHS number, as an ``int``. def generate_random_nhs_number() -> int: """ Returns a random valid NHS number, as an ``int``. """ check_digit = 10 # NHS numbers with this check digit are all invalid while check_digit == 10: digits = [random.randint(1, 9)] # don't start ...
Returns a valid NHS number, as an ``int``, given the first 9 digits. The particular purpose is to make NHS numbers that *look* fake (rather than truly random NHS numbers which might accidentally be real). For example: .. code-block:: none 123456789_ : no; checksum 10 987654321_ : yes,...
Returns a validated NHS number (as an integer) from a string, or ``None`` if it is not valid. It's a 10-digit number, so note that database 32-bit INT values are insufficient; use BIGINT. Python will handle large integers happily. NHS number rules: http://www.datadictionary.nhs.uk/...
Makes an e-mail message. Arguments that can be multiple e-mail addresses are (a) a single e-mail address as a string, or (b) a list of strings (each a single e-mail address), or (c) a comma-separated list of multiple e-mail addresses. Args: from_addr: name of the sender for the "From:" field ...