Beispiel #1
0
def test_cbox_exitcode_0_no_error():
    @cbox.stream()
    def identity(line):
        return line

    with pytest.raises(SystemExit) as err:
        cbox.main(identity, [], StringIO(DATA1), StringIO(), StringIO())
        assert err.status == 0
Beispiel #2
0
def test_cbox_exitcode_2_on_error():
    @cbox.stream()
    def raiser(line):
        raise Exception()

    with pytest.raises(SystemExit) as err:
        cbox.main(raiser, [], StringIO(DATA1), StringIO(), StringIO())
        assert err.status == 2
Beispiel #3
0
def main(argv=None,
         input_stream=stdin,
         output_stream=stdout,
         error_stream=stderr):
    """runs inline function - more info run `cbox --help`"""
    args = _parse_args(argv)
    args_dict = args.__dict__.copy()
    inline_str = args_dict.pop('inline')
    modules = args_dict.pop('modules')

    func = get_inline_func(inline_str, modules, **args_dict)

    return cbox.main(
        func=func,
        argv=[],
        input_stream=input_stream,
        output_stream=output_stream,
        error_stream=error_stream,
        exit=False,
    )
Beispiel #4
0
def run_cli(func, in_data, argv=(), expected_exitcode=0, return_stderr=False):
    """runs `func` using `cbox.run()` and returns its output stream content"""
    outstream = StringIO()
    errstream = StringIO()
    instream = StringIO(in_data)

    exitcode = cbox.main(func,
                         argv,
                         instream,
                         outstream,
                         errstream,
                         exit=False)

    assert expected_exitcode == exitcode

    outstream.seek(0)
    errstream.seek(0)

    if return_stderr:
        return outstream.read(), errstream.read()

    assert not errstream.read()
    return outstream.read()
Beispiel #5
0
        update_user_mapping_table()

    if operation == 'update':
        format_jarvis_streaming_records()
        transfer_original_chatroom_2_useful()
        combine_message_records()
        update_user_mapping_table()

    elif operation == 'download-highrank':
        download_highrank_video(chat_per_min_gte=chat_per_min_gte,
                                clip=clip,
                                duration=duration)

    elif operation == 'clip-video':
        clip_video(video_id=video_id,
                   clip_condition_by=clip_condition_by,
                   duration=duration)

    elif operation == 'statistics-report':
        statistics_report(chat_per_min_gte=chat_per_min_gte, sort_by=sort_by)

    elif operation == 'statistics-wordcount':
        statistics_chatroom_word_count(user=user, n_gram=n_gram)

    elif operation == 'statistics-video-comments':
        statistics_video_comments(video_id=video_id)


if __name__ == '__main__':
    cbox.main(main)
Beispiel #6
0
#!/usr/bin/env python3
import cbox


@cbox.cmd
def hello(name: str):
    """greets a person by its name.

    :param name: the name of the person
    """
    print('hello name {name}!'.format(name=name))


@cbox.cmd
def world(name: str):
    """greets a person by its name.

    :param name: the name of the person
    """
    print('world name {name}!'.format(name=name))


if __name__ == '__main__':
    cbox.main([hello, world])
Beispiel #7
0
#!/usr/bin/env python3
import asyncio

import cbox


@cbox.stream(worker_type='asyncio', workers_window=30)
async def tcping(domain, timeout: int = 3):
    loop = asyncio.get_event_loop()

    fut = asyncio.open_connection(domain, 80, loop=loop)
    try:
        reader, writer = await asyncio.wait_for(fut, timeout=timeout)
        writer.close()
        status = 'up'
    except (OSError, asyncio.TimeoutError):
        status = 'down'

    return '{} is {}'.format(domain, status)


if __name__ == '__main__':
    cbox.main(tcping)
Beispiel #8
0
#!/usr/bin/env python3
import cbox

counter = 0


@cbox.stream()
def head(line, n: int):
    """returns the first `n` lines"""
    global counter
    counter += 1

    if counter > n:
        raise cbox.Stop()  # can also raise StopIteration()
    return line


if __name__ == '__main__':
    cbox.main(head)
Beispiel #9
0
def main():
    cbox.main([init, config, run, stop, status, quick])
Beispiel #10
0
#!/usr/bin/env python3
import cbox


@cbox.stream()
# we can pass default values and use type annotations for correct types
def nth_item(line, n: int = 0):
    """returns the nth item from each line.

    :param n: the number of item position starting from 0
    """
    return line.split()[n]


if __name__ == '__main__':
    cbox.main(nth_item)
Beispiel #11
0
def main():
    cbox.main([init, config, run, stop, status, quick, log, version, i])
Beispiel #12
0
#!/usr/bin/env python3
import cbox


@cbox.stream()
def first(line):
    return line.split()[0]


if __name__ == '__main__':
    cbox.main(first)
Beispiel #13
0
#!/usr/bin/env python3
import codecs
import cbox


@cbox.stream(input_type='chars')
def rot13(char):
    """replace each english letter 13 letters next"""
    return codecs.encode(char, 'rot_13')


if __name__ == '__main__':
    cbox.main(rot13)
Beispiel #14
0
#!/usr/bin/env python3
import re

import cbox


@cbox.stream()
def extract_domains(line):
    """tries to extract all the domains from the input using simple regex"""
    return re.findall(r'(?:\w+\.)+\w+', line) or None  # or None can be omitted


if __name__ == '__main__':
    cbox.main(extract_domains)
Beispiel #15
0
#!/usr/bin/env python3
import cbox


@cbox.cmd
def hello(name: str):
    """greets a person by its name.

    :param name: the name of the person
    """
    print(f'hello {name}!')


if __name__ == '__main__':
    cbox.main(hello)
Beispiel #16
0
    """
    config_handler = Config(ROOT_PATH)
    progress_msg('Setting up config files')
    asyncio.run(config_handler.init())
    asyncio.run(config_handler.export())


@cbox.cmd
def run():
    """run nodes.
    """
    progress_msg('Starting node(s)')
    pro = sub.Popen(["java", "-jar", ROOT_PATH + NODES_DIR + FULL_NODE_DIR + FULL_NODE_JAR, 
            "-c", ROOT_PATH + NODES_DIR + FULL_NODE_DIR + FULL_CONFIG, 
            "--witness"])
    # print('os.getpgid(pro.pid): ', os.getpgid(pro.pid))


@cbox.cmd
def quick():
    logo()
    init('lastest')
    config()
    run()


if __name__ == '__main__':
    ROOT_PATH = os.getcwd()
    cbox.main([init, config, run, quick])

Beispiel #17
0
#!/usr/bin/env python3
import cbox


@cbox.stream()
def numbersonly(line):
    """returns the lines containing only numbers. bad lines reported to stderr.
    if any bad line is detected, exits with exitcode 2.
    """
    if not line.isnumeric():
        raise ValueError('{} is not a number'.format(line))
    return line


if __name__ == '__main__':
    cbox.main(numbersonly)
Beispiel #18
0
#!/usr/bin/env python3
import cbox
import requests


@cbox.stream(worker_type='thread', max_workers=4)
def url_status(line):
    resp = requests.get(line)
    return '{} - {}'.format(line, resp.status_code)


if __name__ == '__main__':
    cbox.main(url_status)