Coverage for pandalone.utils: 98%

# Coverage for pandalone.utils : 98%

## 59 statements 58 run 1 missing 23 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | #! python #-*- coding: utf-8 -*- # # Copyright 2013-2015 European Commission (JRC); # Licensed under the EUPL (the 'Licence'); # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl from __future__ import division, unicode_literals import argparse import os import re import sys from future.moves import collections from past.types import basestring __commit__ = "" # Python-2 compatibility # try: # pragma: no cover FileNotFoundError except NameError: # pragma: no cover FileNotFoundError = IOError # @ReservedAssignment else: # pragma: no cover FileNotFoundError = OSError # @ReservedAssignment def fullmatch_py2(regex, string, flags=0): # NOTE: re.match("(?:" + regex + r")\Z", string, flags=flags) m = re.match(regex, string, flags=flags) if m and m.span()[1] == len(string): return m try: # pragma: no cover from re import fullmatch # @UnusedImport except ImportError: # pragma: no cover fullmatch = fullmatch_py2 ############## # Utilities # def str2bool(v): """ Utility for parsing cmd-line args. :param str v: any of (case insensitive): yes/no, true/false, on/off Example:: >>> str2bool('ON') True >>> str2bool('no') False >>> str2bool('') False >>> str2bool(' ') False >>> str2bool(0) Traceback (most recent call last): ValueError: Invalid str-boolean(0) due to: 'int' object has no attribute 'strip' >>> str2bool(None) Traceback (most recent call last): ValueError: Invalid str-boolean(None) due to: 'NoneType' object has no attribute 'strip' """ try: vv = v.strip().lower() if (vv in ("yes", "true", "on")): return True if (vv in ("no", "false", "off")): return False return bool(vv) except Exception as ex: msg = 'Invalid str-boolean(%s) due to: %s' raise ValueError(msg % (v, ex)) def is_travis(): # pragma: no cover return 'TRAVIS' in os.environ def as_list(o): if isinstance(o, collections.Sequence) and not isinstance(o, basestring): o = list(o) else: o = [o] return o def generate_filenames(filename): f, e = os.path.splitext(filename) yield filename i = 1 while True: yield '%s%i%s' % (f, i, e) i += 1 def make_unique_filename(fname, filegen=generate_filenames): fname_genor = generate_filenames(fname) fname = next(fname_genor) while os.path.exists(fname): fname = next(fname_genor) return fname def ensure_file_ext(fname, ext): """ :param str ext: extension with dot(.) >>> assert ensure_file_ext('foo', '.bar') == 'foo.bar' >>> assert ensure_file_ext('foo.bar', '.bar') == 'foo.bar' >>> assert ensure_file_ext('foo.', '.bar') == 'foo..bar' >>> assert ensure_file_ext('foo.', 'bar') == 'foo.bar' """ _, e = os.path.splitext(fname) if e != ext: return '%s%s' % (fname, ext) return fname def open_file_with_os(fpath): # pragma: no cover # From http://stackoverflow.com/questions/434597/open-document-with-default-application-in-python # and http://www.dwheeler.com/essays/open-files-urls.html import subprocess try: os.startfile(fpath) # @UndefinedVariable except AttributeError: if sys.platform.startswith('darwin'): subprocess.call(('open', fpath)) elif os.name == 'posix': subprocess.call(('xdg-open', fpath)) return class LoggerWriter: """From http://plumberjack.blogspot.gr/2009/09/how-to-treat-logger-like-output-stream.html""" def __init__(self, logger, level): self.logger = logger self.level = level def write(self, msg): if msg: line_endings = ['\r\n', '\n\r', '\n'] for le in line_endings: if msg.endswith(le): msg = msg[:-len(le)] if msg: self.logger.log(self.level, msg) if __name__ == '__main__': raise NotImplementedError