Ejemplo n.º 1
0
def write_file(filename):
    f = None
    try:
        f = open(filename, 'w')
        yield f
    finally:
        if f:
            f.close()
            log.info('File closed: ' + filename)
Ejemplo n.º 2
0
def change_directory(destination):
    """Context manager to change directory back and forth"""
    cwd = os.getcwd()
    try:
        os.chdir(destination)
        log.info('switched to directory: ' + destination)
        yield
    finally:
        os.chdir(cwd)
        log.info('switched back to original directory: ' + cwd)
Ejemplo n.º 3
0
from io import StringIO
from contextlib import redirect_stdout
from contextlib import suppress
from python.log_util.logger import log


class CaptureIO:
    @staticmethod
    def get_help(module_name):
        io_obj = StringIO()
        with redirect_stdout(io_obj):
            with suppress(Exception):
                exec('import ' + module_name)
            exec(f'help({module_name})')
        return io_obj.getvalue()


if __name__ == '__main__':
    help_txt = CaptureIO.get_help('python.log_util.logger')
    log.info('Help result: \n\n' + help_txt)
Ejemplo n.º 4
0
def write_file(filename):
    f = None
    try:
        f = open(filename, 'w')
        yield f
    finally:
        if f:
            f.close()
            log.info('File closed: ' + filename)


if __name__ == '__main__':
    dest = '/home/swadhi/Documents/AWS/aws_notes'
    with change_directory(dest):
        ls_root = os.listdir('.')
        log.info("Contents of directory '{}': ".format(dest))
        [log.debug('  >>> ' + ls) for ls in sorted(ls_root)]

    filename = '/tmp/test.txt'
    with write_file(filename) as file:
        file.write('Swadhikar Chandramohan\n')
        log.info(f'Written line to file: {filename}')

"""
Output:

/usr/bin/python3.6 /home/swadhi/PycharmProjects/pyselenium/python/python_practise/context_manager/cm_func.py
2017-12-24 09:16:31,992: INFO  - switched to directory: /home/swadhi/Documents/AWS/aws_notes
2017-12-24 09:16:31,992: INFO  - Contents of directory '/home/swadhi/Documents/AWS/aws_notes': 
2017-12-24 09:16:31,992: DEBUG -   >>> .git
2017-12-24 09:16:31,992: DEBUG -   >>> dec_03.txt
Tag = namedtuple('Tag', 'TITLE H1 H2 P')


@contextmanager
def show_tag(tag):
    print('<{}>'.format(tag), end='')
    yield
    print('</{}>'.format(tag))


if __name__ == '__main__':
    t = Tag('title', 'h1', 'h2', 'p')

    with show_tag(t.TITLE):
        print("Welcome Page", end='')

    with show_tag(t.P):
        print("Paragraph tag", end='')

    files = ['unknowfile.file', './remfile.txt']
    for file in files:
        with suppress(FileNotFoundError):
            os.remove(file)

    f = io.StringIO()
    with redirect_stdout(f):
        help(pow)
    help_pow = f.getvalue()

    log.info('Help (POW): \n' + help_pow)