Beispiel #1
0
def format_message(args, fmt_str):
    r"""Format a message from a list of arguments and a format string.

    Args:
        args (list, obj): List of arguments or single argument that should be
            formatted using the format string.
        fmt_str (str, bytes): Format string that should be used to format the
            arguments.

    Returns:
        str, bytes: Formatted message. The type will match the type of the
            fmt_str.

    Raises:
        RuntimeError: If the number of arguments does not match the number of
            format fields.

    """
    if not isinstance(args, (tuple, list)):
        args = (args, )
    nfmt = len(extract_formats(fmt_str))
    args_ = []
    if len(args) < nfmt:
        raise RuntimeError("Number of arguments (%d) does not match " %
                           len(args) + "number of format fields (%d)." % nfmt)
    for a0 in args:
        a = units.get_data(a0)
        if np.iscomplexobj(a):
            args_ += [a.real, a.imag]
        else:
            args_.append(a)
    out = backwards.format_bytes(fmt_str, tuple(args_))
    return out
def test_format_bytes():
    r"""Test formating of bytes string."""
    s0 = "%s, %s"
    ans = "one, one"
    arg0 = "one"
    args = (backwards.as_bytes(arg0), backwards.as_unicode(arg0))
    for cvt in [backwards.as_bytes, backwards.as_unicode]:
        res = backwards.format_bytes(cvt(s0), args)
        assert_equal(res, cvt(ans))
def test_AsciiTableComm_nofmt():
    r"""Test read of asciitable without format."""
    test_file = os.path.join(os.getcwd(), 'temp_file.txt')
    rows = [('one', 1, 1.0), ('two', 2, 2.0), ('three', 3, 3.0)]
    lines = [backwards.format_bytes('%5s\t%d\t%f\n', r) for r in rows]
    contents = backwards.as_bytes(''.join(lines))
    with open(test_file, 'wb') as fd:
        fd.write(contents)
    inst = AsciiTableComm.AsciiTableComm('test', test_file, direction='recv')
    inst.open()
    for ans in rows:
        flag, x = inst.recv_dict()
        assert (flag)
        irow = [e for e in ans]
        irow[0] = backwards.as_bytes(irow[0])
        idict = {'f%d' % i: irow[i] for i in range(len(irow))}
        # irow = tuple(irow)
        assert_equal(x, idict)
    flag, x = inst.recv()
    assert (not flag)
    inst.close()
    os.remove(test_file)