Changeset 4021 for trunk/GSASIIfiles.py


Ignore:
Timestamp:
Jun 11, 2019 10:05:07 PM (2 years ago)
Author:
toby
Message:

implement filter for screen messages; start to replace print() with G2Print(); scripting changes for PDF

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIfiles.py

    r4018 r4021  
    4242            pass
    4343    return 0.0
     44
     45G2printLevel = 'all'
     46'''This defines the level of output from calls to :func:`G2Print`,
     47which should  be used in place of print() within this module.
     48Settings for this are 'all', 'warn', 'error' or 'none'. Also see:
     49:func:`G2Print` and :func:`G2SetPrintLevel`.
     50'''
     51
     52def G2SetPrintLevel(level):
     53    '''Set the level of output from calls to :func:`G2Print`, which should
     54    be used in place of print() within GSASII. Settings for the mode are
     55    'all', 'warn', 'error' or 'none'
     56   
     57    :param str level: a string used to set the print level, which may be
     58    'all', 'warn', 'error' or 'none'.
     59    Note that capitalization and extra letters in level are ignored, so
     60    'Warn', 'warnings', etc. will all set the mode to 'warn'
     61    '''
     62    global G2printLevel
     63    for mode in  'all', 'warn', 'error', 'none':
     64        if mode in level.lower():
     65            G2printLevel = mode
     66            return
     67    else:
     68        G2Print('G2SetPrintLevel Error: level={} cannot be interpreted.',
     69                    'Use all, warn, error or none.')
     70       
     71def G2Print(*args,mode=None,**kwargs):
     72    '''Print with filtering based level of output (see :func:`G2SetPrintLevel`).
     73    Use G2Print() as replacement for print().
     74
     75    :param str mode: if specified, this should contain the mode for printing
     76    ('error', 'warn' or anything else). If not specified, the first argument
     77    of the print command (args[0]) should contain the string 'error' for
     78    error messages and 'warn' for warning messages.
     79    '''
     80    if G2printLevel is 'none': return
     81    if mode is None:
     82        testStr = args[0].lower()
     83    else:
     84        testStr = mode[:].lower()
     85    level = 2
     86    for i,mode in enumerate(('error', 'warn')):
     87        if mode in testStr:
     88            level = i
     89            break
     90    if G2printLevel == 'error' and level > 0: return
     91    if G2printLevel == 'warn' and level > 1: return
     92    print(*args,**kwargs)
    4493
    4594def get_python_versions(packagelist):
     
    360409                            readerlist.append(reader)
    361410        except AttributeError:
    362             print ('Import_' + errprefix + ': Attribute Error ' + filename)
     411            G2Print ('Import_' + errprefix + ': Attribute Error ' + filename)
    363412            if traceback:
    364413                traceback.print_exc(file=sys.stdout)
    365414        except Exception as exc:
    366             print ('\nImport_' + errprefix + ': Error importing file ' + filename)
    367             print (u'Error message: {}\n'.format(exc))
     415            G2Print ('\nImport_' + errprefix + ': Error importing file ' + filename)
     416            G2Print (u'Error message: {}\n'.format(exc))
    368417            if traceback:
    369418                traceback.print_exc(file=sys.stdout)
     
    409458                    pass
    410459                except Exception as exc:
    411                     print ('\nExport init: Error substantiating class ' + clss[0])
    412                     print (u'Error message: {}\n'.format(exc))
     460                    G2Print ('\nExport init: Error substantiating class ' + clss[0])
     461                    G2Print (u'Error message: {}\n'.format(exc))
    413462                    if traceback:
    414463                        traceback.print_exc(file=sys.stdout)
     
    416465                exporterlist.append(exporter)
    417466        except AttributeError:
    418             print ('Export Attribute Error ' + filename)
     467            G2Print ('Export Attribute Error ' + filename)
    419468            if traceback:
    420469                traceback.print_exc(file=sys.stdout)
    421470        except Exception as exc:
    422             print ('\nExport init: Error importing file ' + filename)
    423             print (u'Error message: {}\n'.format(exc))
     471            G2Print ('\nExport init: Error importing file ' + filename)
     472            G2Print (u'Error message: {}\n'.format(exc))
    424473            if traceback:
    425474                traceback.print_exc(file=sys.stdout)
     
    564613    parfiles = glob.glob(os.path.join(GSASIIpath.GetConfigValue('Column_Metadata_directory'),'*.par'))
    565614    if len(parfiles) == 0:
    566         print('Sorry, No Column metadata (.par) file found in '+
     615        G2Print('Sorry, No Column metadata (.par) file found in '+
    567616              GSASIIpath.GetConfigValue('Column_Metadata_directory'))
    568617        return {}
     
    574623                break
    575624        else:
    576             print('Warning: No labels definitions found for '+parFil)
     625            G2Print('Warning: No labels definitions found for '+parFil)
    577626            continue
    578627        labels,lbldict,keyCols,keyExp,errors = readColMetadataLabels(lblFil)
     
    582631            continue
    583632        else:
    584             print('Read '+lblFil)
     633            G2Print('Read '+lblFil)
    585634        # scan through each line in this .par file, looking for the matching image rootname
    586635        fp = open(parFil,'Ur')
     
    600649            metadata['par file'] = parFil
    601650            metadata['lbls file'] = lblFil
    602             print("Metadata read from {} line {}".format(parFil,iline+1))
     651            G2Print("Metadata read from {} line {}".format(parFil,iline+1))
    603652            fp.close()
    604653            return metadata
    605654        else:
    606             print("Image {} not found in {}".format(imageName,parFil))
     655            G2Print("Image {} not found in {}".format(imageName,parFil))
    607656            fp.close()
    608657            continue
    609658        fp.close()
    610659    else:
    611         print("Warning: No .par metadata for image {}".format(imageName))
     660        G2Print("Warning: No .par metadata for image {}".format(imageName))
    612661        return {}
    613662
     
    700749        reader.Data['wavelength'] = parParms['wavelength']
    701750    else:
    702         print('Error: wavelength not defined in {}'.format(parParms['lbls file']))
     751        G2Print('Error: wavelength not defined in {}'.format(parParms['lbls file']))
    703752    if "distance" in parParms:
    704753        reader.Data['distance'] = parParms['distance']
    705754        reader.Data['setdist'] = parParms['distance']
    706755    else:
    707         print('Error: distance not defined in {}'.format(parParms['lbls file']))
     756        G2Print('Error: distance not defined in {}'.format(parParms['lbls file']))
    708757
    709758def LoadControls(Slines,data):
     
    778827                primaryReaders.append(rd)
    779828    if len(secondaryReaders) + len(primaryReaders) == 0:
    780         print('Error: No matching format for file '+imagefile)
     829        G2Print('Error: No matching format for file '+imagefile)
    781830        raise Exception('No image read')
    782831    errorReport = ''
     
    796845                raise Exception('No image read. Strange!')
    797846            if GSASIIpath.GetConfigValue('Transpose'):
    798                 print ('Transposing Image!')
     847                G2Print ('Warning: Transposing Image!')
    799848                rd.Image = rd.Image.T
    800849            #rd.readfilename = imagefile
    801850            return rd.Image
    802851    else:
    803         print('Error reading file '+imagefile)
    804         print('Error messages(s)\n'+errorReport)
     852        G2Print('Error reading file '+imagefile)
     853        G2Print('Error messages(s)\n'+errorReport)
    805854        raise Exception('No image read')
    806855
     
    870919            iqfile.write("%15.6g %15.6g\n" % (q,iq))
    871920        iqfile.close()
    872         print (' I(Q) saved to: '+iqfilename)
     921        G2Print (' I(Q) saved to: '+iqfilename)
    873922
    874923    if PDFsaves[1]:     #S(Q)
     
    884933            sqfile.write("%15.6g %15.6g\n" % (q,sq))
    885934        sqfile.close()
    886         print (' S(Q) saved to: '+sqfilename)
     935        G2Print (' S(Q) saved to: '+sqfilename)
    887936
    888937    if PDFsaves[2]:     #F(Q)
     
    898947            fqfile.write("%15.6g %15.6g\n" % (q,fq))
    899948        fqfile.close()
    900         print (' F(Q) saved to: '+fqfilename)
     949        G2Print (' F(Q) saved to: '+fqfilename)
    901950
    902951    if PDFsaves[3]:     #G(R)
     
    912961            grfile.write("%15.6g %15.6g\n" % (r,gr))
    913962        grfile.close()
    914         print (' G(R) saved to: '+grfilename)
     963        G2Print (' G(R) saved to: '+grfilename)
    915964
    916965    if PDFsaves[4]: #pdfGUI file for G(R)
     
    9701019            grfile.write("%15.2F %15.6F\n" % (r,gr))
    9711020        grfile.close()
    972         print (' G(R) saved to: '+grfilename)
     1021        G2Print (' G(R) saved to: '+grfilename)
Note: See TracChangeset for help on using the changeset viewer.