| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# |
| 3 |
# Copyright (c) 2019, the cclib development team |
| 4 |
# |
| 5 |
# This file is part of cclib (http://cclib.github.io) and is distributed under |
| 6 |
# the terms of the BSD 3-Clause License. |
| 7 |
"""Generic output file parser and related tools""" |
| 8 |
|
| 9 |
|
| 10 |
import bz2 |
| 11 |
import fileinput |
| 12 |
import gzip |
| 13 |
import inspect |
| 14 |
import io |
| 15 |
import logging |
| 16 |
import os |
| 17 |
import random |
| 18 |
import sys |
| 19 |
import zipfile |
| 20 |
|
| 21 |
if sys.version_info.major == 2: |
| 22 |
getargspec = inspect.getargspec |
| 23 |
else: |
| 24 |
getargspec = inspect.getfullargspec |
| 25 |
|
| 26 |
import numpy |
| 27 |
|
| 28 |
from cclib.parser import utils |
| 29 |
from cclib.parser.data import ccData |
| 30 |
from cclib.parser.data import ccData_optdone_bool |
| 31 |
|
| 32 |
|
| 33 |
# This seems to avoid a problem with Avogadro. |
| 34 |
logging.logMultiprocessing = 0 |
| 35 |
|
| 36 |
|
| 37 |
class myBZ2File(bz2.BZ2File): |
| 38 |
"""Return string instead of bytes""" |
| 39 |
def __next__(self): |
| 40 |
line = super(bz2.BZ2File, self).__next__() |
| 41 |
return line.decode("ascii", "replace") |
| 42 |
|
| 43 |
def next(self): |
| 44 |
line = self.__next__() |
| 45 |
return line |
| 46 |
|
| 47 |
|
| 48 |
class myGzipFile(gzip.GzipFile): |
| 49 |
"""Return string instead of bytes""" |
| 50 |
def __next__(self): |
| 51 |
super_ob = super(gzip.GzipFile, self) |
| 52 |
# seemingly different versions of gzip can have either next or __next__ |
| 53 |
if hasattr(super_ob, 'next'): |
| 54 |
line = super_ob.next() |
| 55 |
else: |
| 56 |
line = super_ob.__next__() |
| 57 |
return line.decode("ascii", "replace") |
| 58 |
|
| 59 |
def next(self): |
| 60 |
line = self.__next__() |
| 61 |
return line |
| 62 |
|
| 63 |
|
| 64 |
class myFileinputFile(fileinput.FileInput): |
| 65 |
"""Implement next() method""" |
| 66 |
def next(self): |
| 67 |
line = next(self) |
| 68 |
return line |
| 69 |
|
| 70 |
|
| 71 |
class FileWrapper(object): |
| 72 |
"""Wrap a file-like object or stream with some custom tweaks""" |
| 73 |
|
| 74 |
def __init__(self, source, pos=0): |
| 75 |
|
| 76 |
self.src = source |
| 77 |
|
| 78 |
# Most file-like objects have seek and tell methods, but streams returned |
| 79 |
# by urllib.urlopen in Python2 do not, which will raise an AttributeError |
| 80 |
# in this code. On the other hand, in Python3 these methods do exist since |
| 81 |
# urllib uses the stream class in the io library, but they raise a different |
| 82 |
# error, namely io.UnsupportedOperation. That is why it is hard to be more |
| 83 |
# specific with except block here. |
| 84 |
try: |
| 85 |
self.src.seek(0, 2) |
| 86 |
self.size = self.src.tell() |
| 87 |
self.src.seek(pos, 0) |
| 88 |
|
| 89 |
except (AttributeError, IOError, io.UnsupportedOperation): |
| 90 |
# Stream returned by urllib should have size information. |
| 91 |
if hasattr(self.src, 'headers') and 'content-length' in self.src.headers: |
| 92 |
self.size = int(self.src.headers['content-length']) |
| 93 |
else: |
| 94 |
self.size = pos |
| 95 |
|
| 96 |
# Assume the position is what was passed to the constructor. |
| 97 |
self.pos = pos |
| 98 |
|
| 99 |
def next(self): |
| 100 |
line = next(self.src) |
| 101 |
self.pos += len(line) |
| 102 |
return line |
| 103 |
|
| 104 |
def __next__(self): |
| 105 |
return self.next() |
| 106 |
|
| 107 |
def __iter__(self): |
| 108 |
return self |
| 109 |
|
| 110 |
def close(self): |
| 111 |
self.src.close() |
| 112 |
|
| 113 |
def seek(self, pos, ref): |
| 114 |
|
| 115 |
# If we are seeking to end, we can emulate it usually. As explained above, |
| 116 |
# we cannot be too specific with the except clause due to differences |
| 117 |
# between Python2 and 3. Yet another reason to drop Python 2 soon! |
| 118 |
try: |
| 119 |
self.src.seek(pos, ref) |
| 120 |
except: |
| 121 |
if ref == 2: |
| 122 |
self.src.read() |
| 123 |
else: |
| 124 |
raise |
| 125 |
|
| 126 |
if ref == 0: |
| 127 |
self.pos = pos |
| 128 |
if ref == 1: |
| 129 |
self.pos += pos |
| 130 |
if ref == 2 and hasattr(self, 'size'): |
| 131 |
self.pos = self.size |
| 132 |
|
| 133 |
|
| 134 |
def openlogfile(filename, object=None): |
| 135 |
"""Return a file object given a filename or if object specified decompresses it |
| 136 |
if needed and wrap it up. |
| 137 |
|
| 138 |
Given the filename or file object of a log file or a gzipped, zipped, or bzipped |
| 139 |
log file, this function returns a file-like object. |
| 140 |
|
| 141 |
Given a list of filenames, this function returns a FileInput object, |
| 142 |
which can be used for seamless iteration without concatenation. |
| 143 |
""" |
| 144 |
|
| 145 |
# If there is a single string argument given. |
| 146 |
if type(filename) in [str, str]: |
| 147 |
|
| 148 |
extension = os.path.splitext(filename)[1] |
| 149 |
|
| 150 |
if extension == ".gz": |
| 151 |
fileobject = myGzipFile(filename, "r", fileobj=object) |
| 152 |
|
| 153 |
elif extension == ".zip": |
| 154 |
zip = zipfile.ZipFile(object, "r") if object else zipfile.ZipFile(filename, "r") |
| 155 |
assert len(zip.namelist()) == 1, "ERROR: Zip file contains more than 1 file" |
| 156 |
fileobject = io.StringIO(zip.read(zip.namelist()[0]).decode("ascii", "ignore")) |
| 157 |
|
| 158 |
elif extension in ['.bz', '.bz2']: |
| 159 |
# Module 'bz2' is not always importable. |
| 160 |
assert bz2 is not None, "ERROR: module bz2 cannot be imported" |
| 161 |
fileobject = myBZ2File(object, "r") if object else myBZ2File(filename, "r") |
| 162 |
|
| 163 |
else: |
| 164 |
# Assuming that object is text file encoded in utf-8 |
| 165 |
fileobject = io.StringIO(object.decode('utf-8')) if object \ |
| 166 |
else FileWrapper(io.open(filename, "r", errors='ignore')) |
| 167 |
|
| 168 |
return fileobject |
| 169 |
|
| 170 |
elif hasattr(filename, "__iter__"): |
| 171 |
|
| 172 |
# This is needed, because fileinput will assume stdin when filename is empty. |
| 173 |
if len(filename) == 0: |
| 174 |
return None |
| 175 |
|
| 176 |
# Compression (gzip and bzip) is supported as of Python 2.5. |
| 177 |
if sys.version_info[0] >= 2 and sys.version_info[1] >= 5: |
| 178 |
fileobject = fileinput.input(filename, openhook=fileinput.hook_compressed) |
| 179 |
else: |
| 180 |
fileobject = myFileinputFile(filename) |
| 181 |
|
| 182 |
return fileobject |
| 183 |
|
| 184 |
|
| 185 |
class Logfile(object): |
| 186 |
"""Abstract class for logfile objects. |
| 187 |
|
| 188 |
Subclasses defined by cclib: |
| 189 |
ADF, DALTON, GAMESS, GAMESSUK, Gaussian, Jaguar, Molpro, MOPAC, |
| 190 |
NWChem, ORCA, Psi, Q-Chem |
| 191 |
""" |
| 192 |
|
| 193 |
def __init__(self, source, loglevel=logging.ERROR, logname="Log", |
| 194 |
logstream=sys.stderr, datatype=ccData_optdone_bool, **kwds): |
| 195 |
"""Initialise the Logfile object. |
| 196 |
|
| 197 |
This should be called by a subclass in its own __init__ method. |
| 198 |
|
| 199 |
Inputs: |
| 200 |
source - a logfile, list of logfiles, or stream with at least a read method |
| 201 |
loglevel - integer corresponding to a log level from the logging module |
| 202 |
logname - name of the source logfile passed to this constructor |
| 203 |
logstream - where to output the logging information |
| 204 |
datatype - class to use for gathering data attributes |
| 205 |
""" |
| 206 |
|
| 207 |
# Set the filename to source if it is a string or a list of strings, which are |
| 208 |
# assumed to be filenames. Otherwise, assume the source is a file-like object |
| 209 |
# if it has a read method, and we will try to use it like a stream. |
| 210 |
self.isfileinput = False |
| 211 |
if isinstance(source, str): |
| 212 |
self.filename = source |
| 213 |
self.isstream = False |
| 214 |
elif isinstance(source, list) and all([isinstance(s, str) for s in source]): |
| 215 |
self.filename = source |
| 216 |
self.isstream = False |
| 217 |
elif isinstance(source, fileinput.FileInput): |
| 218 |
self.filename = source |
| 219 |
self.isstream = False |
| 220 |
self.isfileinput = True |
| 221 |
elif hasattr(source, "read"): |
| 222 |
self.filename = "stream %s" % str(type(source)) |
| 223 |
self.isstream = True |
| 224 |
self.stream = source |
| 225 |
else: |
| 226 |
raise ValueError("Unexpected source type.") |
| 227 |
|
| 228 |
# Set up the logger. |
| 229 |
# Note that calling logging.getLogger() with one name always returns the same instance. |
| 230 |
# Presently in cclib, all parser instances of the same class use the same logger, |
| 231 |
# which means that care needs to be taken not to duplicate handlers. |
| 232 |
self.loglevel = loglevel |
| 233 |
self.logname = logname |
| 234 |
self.logger = logging.getLogger('%s %s' % (self.logname, self.filename)) |
| 235 |
self.logger.setLevel(self.loglevel) |
| 236 |
if len(self.logger.handlers) == 0: |
| 237 |
handler = logging.StreamHandler(logstream) |
| 238 |
handler.setFormatter(logging.Formatter("[%(name)s %(levelname)s] %(message)s")) |
| 239 |
self.logger.addHandler(handler) |
| 240 |
|
| 241 |
# Set up the metadata. |
| 242 |
if not hasattr(self, "metadata"): |
| 243 |
self.metadata = {} |
| 244 |
self.metadata["package"] = self.logname |
| 245 |
self.metadata["methods"] = [] |
| 246 |
# Indicate if the computation has completed successfully |
| 247 |
self.metadata['success'] = False |
| 248 |
|
| 249 |
|
| 250 |
# Periodic table of elements. |
| 251 |
self.table = utils.PeriodicTable() |
| 252 |
|
| 253 |
# This is the class that will be used in the data object returned by parse(), and should |
| 254 |
# normally be ccData or a subclass of it. |
| 255 |
self.datatype = datatype |
| 256 |
|
| 257 |
# Change the class used if we want optdone to be a list or if the 'future' option |
| 258 |
# is used, which might have more consequences in the future. |
| 259 |
optdone_as_list = kwds.get("optdone_as_list", False) or kwds.get("future", False) |
| 260 |
optdone_as_list = optdone_as_list if isinstance(optdone_as_list, bool) else False |
| 261 |
if optdone_as_list: |
| 262 |
self.datatype = ccData |
| 263 |
# Parsing of Natural Orbitals and Natural Spin Orbtials into one attribute |
| 264 |
self.unified_no_nso = kwds.get("future",False) |
| 265 |
|
| 266 |
def __setattr__(self, name, value): |
| 267 |
|
| 268 |
# Send info to logger if the attribute is in the list of attributes. |
| 269 |
if name in ccData._attrlist and hasattr(self, "logger"): |
| 270 |
|
| 271 |
# Call logger.info() only if the attribute is new. |
| 272 |
if not hasattr(self, name): |
| 273 |
if type(value) in [numpy.ndarray, list]: |
| 274 |
self.logger.info("Creating attribute %s[]" % name) |
| 275 |
else: |
| 276 |
self.logger.info("Creating attribute %s: %s" % (name, str(value))) |
| 277 |
|
| 278 |
# Set the attribute. |
| 279 |
object.__setattr__(self, name, value) |
| 280 |
|
| 281 |
def parse(self, progress=None, fupdate=0.05, cupdate=0.002): |
| 282 |
"""Parse the logfile, using the assumed extract method of the child.""" |
| 283 |
|
| 284 |
# Check that the sub-class has an extract attribute, |
| 285 |
# that is callable with the proper number of arguemnts. |
| 286 |
if not hasattr(self, "extract"): |
| 287 |
raise AttributeError("Class %s has no extract() method." % self.__class__.__name__) |
| 288 |
if not callable(self.extract): |
| 289 |
raise AttributeError("Method %s._extract not callable." % self.__class__.__name__) |
| 290 |
if len(getargspec(self.extract)[0]) != 3: |
| 291 |
raise AttributeError("Method %s._extract takes wrong number of arguments." % self.__class__.__name__) |
| 292 |
|
| 293 |
# Save the current list of attributes to keep after parsing. |
| 294 |
# The dict of self should be the same after parsing. |
| 295 |
_nodelete = list(set(self.__dict__.keys())) |
| 296 |
|
| 297 |
# Initiate the FileInput object for the input files. |
| 298 |
# Remember that self.filename can be a list of files. |
| 299 |
if not self.isstream: |
| 300 |
if not self.isfileinput: |
| 301 |
inputfile = openlogfile(self.filename) |
| 302 |
else: |
| 303 |
inputfile = self.filename |
| 304 |
else: |
| 305 |
inputfile = FileWrapper(self.stream) |
| 306 |
|
| 307 |
# Intialize self.progress |
| 308 |
is_compressed = isinstance(inputfile, myGzipFile) or isinstance(inputfile, myBZ2File) |
| 309 |
if progress and not (is_compressed): |
| 310 |
self.progress = progress |
| 311 |
self.progress.initialize(inputfile.size) |
| 312 |
self.progress.step = 0 |
| 313 |
self.fupdate = fupdate |
| 314 |
self.cupdate = cupdate |
| 315 |
|
| 316 |
# Maybe the sub-class has something to do before parsing. |
| 317 |
self.before_parsing() |
| 318 |
|
| 319 |
# Loop over lines in the file object and call extract(). |
| 320 |
# This is where the actual parsing is done. |
| 321 |
for line in inputfile: |
| 322 |
self.updateprogress(inputfile, "Unsupported information", cupdate) |
| 323 |
|
| 324 |
# This call should check if the line begins a section of extracted data. |
| 325 |
# If it does, it parses some lines and sets the relevant attributes (to self). |
| 326 |
# Any attributes can be freely set and used across calls, however only those |
| 327 |
# in data._attrlist will be moved to final data object that is returned. |
| 328 |
try: |
| 329 |
self.extract(inputfile, line) |
| 330 |
except StopIteration: |
| 331 |
self.logger.error("Unexpectedly encountered end of logfile.") |
| 332 |
break |
| 333 |
|
| 334 |
# Close input file object. |
| 335 |
if not self.isstream: |
| 336 |
inputfile.close() |
| 337 |
|
| 338 |
# Maybe the sub-class has something to do after parsing. |
| 339 |
self.after_parsing() |
| 340 |
|
| 341 |
# If atomcoords were not parsed, but some input coordinates were ("inputcoords"). |
| 342 |
# This is originally from the Gaussian parser, a regression fix. |
| 343 |
if not hasattr(self, "atomcoords") and hasattr(self, "inputcoords"): |
| 344 |
self.atomcoords = numpy.array(self.inputcoords, 'd') |
| 345 |
|
| 346 |
# Set nmo if not set already - to nbasis. |
| 347 |
if not hasattr(self, "nmo") and hasattr(self, "nbasis"): |
| 348 |
self.nmo = self.nbasis |
| 349 |
|
| 350 |
# Create a default coreelectrons array, unless it's impossible |
| 351 |
# to determine. |
| 352 |
if not hasattr(self, "coreelectrons") and hasattr(self, "natom"): |
| 353 |
self.coreelectrons = numpy.zeros(self.natom, "i") |
| 354 |
if hasattr(self, "incorrect_coreelectrons"): |
| 355 |
self.__delattr__("coreelectrons") |
| 356 |
|
| 357 |
# Create the data object we want to return. This is normally ccData, but can be changed |
| 358 |
# by passing the datatype argument to the constructor. All supported cclib attributes |
| 359 |
# are copied to this object, but beware that in order to be moved an attribute must be |
| 360 |
# included in the data._attrlist of ccData (or whatever else). |
| 361 |
# There is the possibility of passing assitional argument via self.data_args, but |
| 362 |
# we use this sparingly in cases where we want to limit the API with options, etc. |
| 363 |
data = self.datatype(attributes=self.__dict__) |
| 364 |
|
| 365 |
# Now make sure that the cclib attributes in the data object are all the correct type, |
| 366 |
# including arrays and lists of arrays. |
| 367 |
data.arrayify() |
| 368 |
|
| 369 |
# Delete all temporary attributes (including cclib attributes). |
| 370 |
# All attributes should have been moved to a data object, which will be returned. |
| 371 |
for attr in list(self.__dict__.keys()): |
| 372 |
if not attr in _nodelete: |
| 373 |
self.__delattr__(attr) |
| 374 |
|
| 375 |
# Perform final checks on values of attributes. |
| 376 |
data.check_values(logger=self.logger) |
| 377 |
|
| 378 |
# Update self.progress as done. |
| 379 |
if hasattr(self, "progress"): |
| 380 |
self.progress.update(inputfile.size, "Done") |
| 381 |
|
| 382 |
return data |
| 383 |
|
| 384 |
def before_parsing(self): |
| 385 |
"""Set parser-specific variables and do other initial things here.""" |
| 386 |
pass |
| 387 |
|
| 388 |
def after_parsing(self): |
| 389 |
"""Correct data or do parser-specific validation after parsing is finished.""" |
| 390 |
pass |
| 391 |
|
| 392 |
def updateprogress(self, inputfile, msg, xupdate=0.05): |
| 393 |
"""Update progress.""" |
| 394 |
|
| 395 |
if hasattr(self, "progress") and random.random() < xupdate: |
| 396 |
newstep = inputfile.pos |
| 397 |
if newstep != self.progress.step: |
| 398 |
self.progress.update(newstep, msg) |
| 399 |
self.progress.step = newstep |
| 400 |
|
| 401 |
def normalisesym(self, symlabel): |
| 402 |
"""Standardise the symmetry labels between parsers. |
| 403 |
|
| 404 |
This method should be overwritten by individual parsers, and should |
| 405 |
contain appropriate doctests. If is not overwritten, this is detected |
| 406 |
as an error by unit tests. |
| 407 |
""" |
| 408 |
raise NotImplementedError("normalisesym(self, symlabel) must be overriden by the parser.") |
| 409 |
|
| 410 |
def float(self, number): |
| 411 |
"""Convert a string to a float. |
| 412 |
|
| 413 |
This method should perform certain checks that are specific to cclib, |
| 414 |
including avoiding the problem with Ds instead of Es in scientific notation. |
| 415 |
Another point is converting string signifying numerical problems (*****) |
| 416 |
to something we can manage (Numpy's NaN). |
| 417 |
""" |
| 418 |
|
| 419 |
if list(set(number)) == ['*']: |
| 420 |
return numpy.nan |
| 421 |
|
| 422 |
return float(number.replace("D", "E")) |
| 423 |
|
| 424 |
def new_internal_job(self): |
| 425 |
"""Delete attributes that can be problematic in multistep jobs. |
| 426 |
|
| 427 |
TODO: instead of this hack, parse each job in a multistep comptation |
| 428 |
as a different ccData object (this is for 2.x). |
| 429 |
|
| 430 |
Some computations are actually sequences of several jobs, and some |
| 431 |
attributes won't work well if parsed across jobs. There include: |
| 432 |
mpenergies: if different jobs go to different orders then |
| 433 |
these won't be consistent and can't be converted |
| 434 |
to an array easily |
| 435 |
""" |
| 436 |
for name in ("mpenergies",): |
| 437 |
if hasattr(self, name): |
| 438 |
delattr(self, name) |
| 439 |
|
| 440 |
def set_attribute(self, name, value, check_change=True): |
| 441 |
"""Set an attribute and perform an optional check when it already exists. |
| 442 |
|
| 443 |
Note that this can be used for scalars and lists alike, whenever we want |
| 444 |
to set a value for an attribute. |
| 445 |
|
| 446 |
Parameters |
| 447 |
---------- |
| 448 |
name: str |
| 449 |
The name of the attribute. |
| 450 |
value: str |
| 451 |
The value for the attribute. |
| 452 |
check_change: bool |
| 453 |
By default we want to check that the value does not change |
| 454 |
if the attribute already exists. |
| 455 |
""" |
| 456 |
if check_change and hasattr(self, name): |
| 457 |
try: |
| 458 |
numpy.testing.assert_equal(getattr(self, name), value) |
| 459 |
except AssertionError: |
| 460 |
self.logger.warning("Attribute %s changed value (%s -> %s)" % (name, getattr(self, name), value)) |
| 461 |
|
| 462 |
setattr(self, name, value) |
| 463 |
|
| 464 |
def append_attribute(self, name, value): |
| 465 |
"""Appends a value to an attribute.""" |
| 466 |
|
| 467 |
if not hasattr(self, name): |
| 468 |
self.set_attribute(name, []) |
| 469 |
getattr(self, name).append(value) |
| 470 |
|
| 471 |
def extend_attribute(self, name, values): |
| 472 |
"""Appends an iterable of values to an attribute.""" |
| 473 |
|
| 474 |
if not hasattr(self, name): |
| 475 |
self.set_attribute(name, []) |
| 476 |
getattr(self, name).extend(values) |
| 477 |
|
| 478 |
def _assign_coreelectrons_to_element(self, element, ncore, |
| 479 |
ncore_is_total_count=False): |
| 480 |
"""Assign core electrons to all instances of the element. |
| 481 |
|
| 482 |
It's usually reasonable to do this for all atoms of a given element, |
| 483 |
because mixed usage isn't normally allowed within elements. |
| 484 |
|
| 485 |
Parameters |
| 486 |
---------- |
| 487 |
element: str |
| 488 |
the chemical element to set coreelectrons for |
| 489 |
ncore: int |
| 490 |
the number of core electrons |
| 491 |
ncore_is_total_count: bool |
| 492 |
whether the ncore argument is the total count, in which case it is |
| 493 |
divided by the number of atoms of this element |
| 494 |
""" |
| 495 |
atomsymbols = [self.table.element[atomno] for atomno in self.atomnos] |
| 496 |
indices = [i for i, el in enumerate(atomsymbols) if el == element] |
| 497 |
if ncore_is_total_count: |
| 498 |
ncore = ncore // len(indices) |
| 499 |
|
| 500 |
if not hasattr(self, 'coreelectrons'): |
| 501 |
self.coreelectrons = numpy.zeros(self.natom, 'i') |
| 502 |
self.coreelectrons[indices] = ncore |
| 503 |
|
| 504 |
def skip_lines(self, inputfile, sequence): |
| 505 |
"""Read trivial line types and check they are what they are supposed to be. |
| 506 |
|
| 507 |
This function will read len(sequence) lines and do certain checks on them, |
| 508 |
when the elements of sequence have the appropriate values. Currently the |
| 509 |
following elements trigger checks: |
| 510 |
'blank' or 'b' - the line should be blank |
| 511 |
'dashes' or 'd' - the line should contain only dashes (or spaces) |
| 512 |
'equals' or 'e' - the line should contain only equal signs (or spaces) |
| 513 |
'stars' or 's' - the line should contain only stars (or spaces) |
| 514 |
""" |
| 515 |
|
| 516 |
expected_characters = { |
| 517 |
'-': ['dashes', 'd'], |
| 518 |
'=': ['equals', 'e'], |
| 519 |
'*': ['stars', 's'], |
| 520 |
} |
| 521 |
|
| 522 |
lines = [] |
| 523 |
for expected in sequence: |
| 524 |
|
| 525 |
# Read the line we want to skip. |
| 526 |
line = next(inputfile) |
| 527 |
|
| 528 |
# Blank lines are perhaps the most common thing we want to check for. |
| 529 |
if expected in ["blank", "b"]: |
| 530 |
try: |
| 531 |
assert line.strip() == "" |
| 532 |
except AssertionError: |
| 533 |
frame, fname, lno, funcname, funcline, index = inspect.getouterframes(inspect.currentframe())[1] |
| 534 |
parser = fname.split('/')[-1] |
| 535 |
msg = "In %s, line %i, line not blank as expected: %s" % (parser, lno, line.strip()) |
| 536 |
self.logger.warning(msg) |
| 537 |
|
| 538 |
# All cases of heterogeneous lines can be dealt with by the same code. |
| 539 |
for character, keys in expected_characters.items(): |
| 540 |
if expected in keys: |
| 541 |
try: |
| 542 |
assert all([c == character for c in line.strip() if c != ' ']) |
| 543 |
except AssertionError: |
| 544 |
frame, fname, lno, funcname, funcline, index = inspect.getouterframes(inspect.currentframe())[1] |
| 545 |
parser = fname.split('/')[-1] |
| 546 |
msg = "In %s, line %i, line not all %s as expected: %s" % (parser, lno, keys[0], line.strip()) |
| 547 |
self.logger.warning(msg) |
| 548 |
continue |
| 549 |
|
| 550 |
# Save the skipped line, and we will return the whole list. |
| 551 |
lines.append(line) |
| 552 |
|
| 553 |
return lines |
| 554 |
|
| 555 |
skip_line = lambda self, inputfile, expected: self.skip_lines(inputfile, [expected]) |