Source code for pylib.helper

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Helper objects.

:Date: 2020-01-01

.. module:: helper
  :platform: *nix, Windows
  :synopsis: Helper objects.

.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
"""
import os
import time
from contextlib import ContextDecorator

[docs]class timeit(ContextDecorator): """Meassure time for a function or code block. :param description: description for the function or code block used for the print-out :type description: str :Example: >>> with timeit('section_test'): ... # code section_test took 0.006 ms :: @timeit('func') def func(): # code >>> func() func took 0.006 ms """ def __init__(self, description=None): self.description = description def __enter__(self): self.start_time = time.time() return self # to use as: with Timit() as t: def __exit__(self, *exc): # exc: type, value, traceback elapsed_time_ms = (time.time() - self.start_time) * 1000 print('{:s} took {:.3f} ms'.format(self.description, elapsed_time_ms)) return False
[docs]class cd: """Context manager for changing the current working directory :param new_path: the directory to change into :type new_path: string :Example: :: # enter the directory and run some code: with cd("~/tmp"): # we are now in ~/tmp # code # outside the context manager we are back where we started. """ def __init__(self, new_path): self.new_path = os.path.expanduser(new_path) def __enter__(self): self.saved_path = os.getcwd() os.chdir(self.new_path) def __exit__(self, etype, value, traceback): os.chdir(self.saved_path)
[docs]def run_file(file_name): """Run a file. Inside a pythin interpreter it changes to the directory of the file and after excuting the file it changes back to the working directory before. :param file_name: the file to execute :type file_name: string """ workdir = os.path.dirname(os.path.abspath(file_name)) with cd(workdir): exec(open(file_name).read())