defs.html


001| """Baseball Charts - Definitions & Common Functions.
001| 
001| Classes:
001|     CsvBaseballData (csvfile)       ~CSV baseball data file base file (abstract)
001| 
001|         CsvMlbSeason                ~season data on all 30 teams
001| 
001|         CsvTeamGames                ~team game logs
001|         CsvTeamGamesBatting         ~team game logs, batting
001|         CsvTeamGamesPitching        ~team game logs, pitching
001| 
001|         CsvTeamSeasons              ~team stats, all seasons
001|         CsvTeamSeasonsBatting       ~team stats, all seasons, batting
001|         CsvTeamSeasonsPitching      ~team stats, all seasons, pitching
001| 
001|         CsvMlbSeasonsBatting        ~batting in all MLB seasons (from 1900)
001|         CsvMlbSeasonsPitching       ~pitching in all MLB seasons (from 1900)
001| 
001|     ringbuff (list)                 ~basic ring buffer
001| 
001| Data:
001|     DefaultYear                     ~default year for charts and reports
001|     MlbTeams                        ~basic info for all 30 MLB teams
001|     TwinsCode                       ~code for the Twins
001|     TwinsBlue                       ~hex color for the Twins
001|     Opponents                       ~hex color for the Opponents
001| 
001| Functions:
001|     ConvertDate (dt_str, dt_yr)     ~convert date string to date object
001|     RoundUp (N,sep)                 ~return N rounded up by sep
001|     RoundDown (N,sep)               ~return N rounded down by sep
001|     RandColor                       ~return a random color in #rrggbb format
001|     prn (S, file)                   ~print S to Log, stdout, and (optionally) a file
001|     dispatch (cmd, **kwargs)        ~module dispatch
001| 
001| Commands:
001|     dmp         do_csv_file_dump    ~dump CSV file contents to HTML file
001|     csv         do_test_csv         ~test the CSV classes
001|     test        do_test             ~test
001| 
001| """

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import datetime
007| from files import csvfile
008| from logger import logger,info,debug,trace
009| from goodies import KWARG, typename
010| from webpage import WebPage
011| ####################################################################################################
012| HtmlPath = r'C:\CJS\www\root\pub\bb\{year}'
013| BasePath = r'C:\CJS\prj\Python\app\baseball'
014| DataPath = path.join(BasePath, 'dat')
015| ImgsPath = path.join(BasePath, 'img')
016| ListPath = path.join(BasePath, 'out')
017| Log = logger('BB:defs')
018| Now = datetime.now()
019| 
020| CMND = ''
021| ARGS = {
022|     #'team':'twins',
023|     #'year':'2025',
024|     #'fpath': BasePath,
025| }
026| 
027| 
028| ##------------------------------------------------------------------------------------------------##
029| DefaultYear = Now.year
030| 
031| ##------------------------------------------------------------------------------------------------##
032| """MLB Team Info. 0:Lg, 1:Dv, 2:Name, 3:Location, 4:code."""
033| MlbTeams = {
034|     'mariners':  ('AL', 'W', 'Mariners' , 'Seattle'      , 'sea', ),
035|     'athletics': ('AL', 'W', 'Athletics', 'Oakland'      , 'oak', ),
036|     'angels':    ('AL', 'W', 'Angels'   , 'Anaheim'      , 'ana', ),
037|     'rangers':   ('AL', 'W', 'Rangers'  , 'Texas'        , 'tex', ),
038|     'astros':    ('AL', 'W', 'Astros'   , 'Houston'      , 'hou', ),
039| 
040|     'twins':     ('AL', 'C', 'Twins'    , 'Minnesota'    , 'min', ),
041|     'royals':    ('AL', 'C', 'Royals'   , 'Kansas City'  , 'kca', ),
042|     'white_sox': ('AL', 'C', 'White Sox', 'Chicago'      , 'cha', ),
043|     'tigers':    ('AL', 'C', 'Tigers'   , 'Detroit'      , 'det', ),
044|     'guardians': ('AL', 'C', 'Guardians', 'Cleveland'    , 'cle', ),
045| 
046|     'blue_jays': ('AL', 'E', 'Blue Jays', 'Toronto'      , 'tor', ),
047|     'red_sox':   ('AL', 'E', 'Red Sox'  , 'Boston'       , 'bos', ),
048|     'yankees':   ('AL', 'E', 'Yankees'  , 'New York'     , 'nya', ),
049|     'orioles':   ('AL', 'E', 'Orioles'  , 'Baltimore'    , 'bal', ),
050|     'rays':      ('AL', 'E', 'Rays'     , 'Tampa Bay'    , 'tba', ),
051| 
052|     'giants':    ('NL', 'W', 'Giants'   , 'San Francisco', 'sfn', ),
053|     'dodgers':   ('NL', 'W', 'Dodgers'  , 'Los Angeles'  , 'lan', ),
054|     'padres':    ('NL', 'W', 'Padres'   , 'San Diego'    , 'sdn', ),
055|     'rockies':   ('NL', 'W', 'Rockies'  , 'Colorado'     , 'col', ),
056|     'dbacks':    ('NL', 'W', 'Diamondbacks','Arizona'    , 'ari', ),
057| 
058|     'brewers':   ('NL', 'C', 'Brewers'  , 'Milwaukee'    , 'mil', ),
059|     'reds':      ('NL', 'C', 'Reds'     , 'Cincinnati'   , 'cin', ),
060|     'pirates':   ('NL', 'C', 'Pirates'  , 'Pittsburgh'   , 'pit', ),
061|     'cubs':      ('NL', 'C', 'Cubs'     , 'Chicago'      , 'chn', ),
062|     'cardinals': ('NL', 'C', 'Cardinals', 'St. Louis'    , 'sln', ),
063| 
064|     'mets':      ('NL', 'E', 'Mets'     , 'New York'     , 'nyn', ),
065|     'phillies':  ('NL', 'E', 'Phillies' , 'Philadelphia' , 'phi', ),
066|     'nationals': ('NL', 'E', 'Nationals', 'Washington'   , 'was', ),
067|     'braves':    ('NL', 'E', 'Braves'   , 'Atlanta'      , 'atl', ),
068|     'marlins':   ('NL', 'E', 'Marlins'  , 'Miami'        , 'mia', ),
069| }
070| 
071| ##------------------------------------------------------------------------------------------------##
072| TwinsCode = 'twins'
073| TwinsBlue = '#3366ff'
074| Opponents = '#cc6633'
075| 
076| ##------------------------------------------------------------------------------------------------##
077| """Return a randomized color string in form "#xxxxxx", where "x" are hex digits."""
078| 
079| RandColor = lambda: f'#{randint(0,255):02x}{randint(0,255):02x}{randint(0,255):02x}'
080| 
081| 
082| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
083| class CsvBaseballData (csvfile):
084|     """Baseball CSV Data File (base class).
084| 
084| Subclass of files.cvsfile for Comma-Separated Value (CSV) files.
084| As with all file objects from files, initialize with a filename.
084| When initialized, automatically loads the CSV data from the file.
084| 
084| Methods:
084|     get_column_index (name)                 ~return the index of a column
084|     get_column_data (name, reverse)         ~return column data
084|     get_column_data_int (name, reverse)     ~return column data (integer)
084|     get_column_data_float (name, reverse)   ~return column data (float)
084|     get_column_data_date (name, reverse)    ~return column data (date)
084| 
084| """

085|     def __init__ (self, filename, log=None):
086|         """Initialize new instance."""
087|         super().__init__(filename, log=log)
088|         self.load()
089|         Log.info()
090| 
091|     def get_column_index (self, column_name) -> int:
092|         """Return the index of a column."""
093|         # Treat ints as indexes...
094|         if isinstance(column_name, int):
095|             return column_name
096|         # Return the index of the named column...
097|         return self.hdrs.index(column_name)
098| 
099|     def get_column_data (self, column_name, reverse=False) -> list:
100|         """Return a list of a column's data."""
101|         ix = self.get_column_index(column_name)
102|         if reverse:
103|             return [row[ix].strip() for row in reversed(self)]
104|         else:
105|             return [row[ix].strip() for row in self]
106| 
107|     def get_column_data_int (self, column_name, reverse=False) -> list:
108|         """Return a list of a column's data (integer)."""
109|         ix = self.get_column_index(column_name)
110|         if reverse:
111|             return [int(row[ix].strip()) for row in reversed(self)]
112|         else:
113|             return [int(row[ix].strip()) for row in self]
114| 
115|     def get_column_data_float (self, column_name, reverse=False) -> list:
116|         """Return a list of a column's data (float)."""
117|         ix = self.get_column_index(column_name)
118|         if reverse:
119|             return [float(row[ix].strip()) for row in reversed(self)]
120|         else:
121|             return [float(row[ix].strip()) for row in self]
122| 
123|     def get_column_data_date (self, column_name, reverse=False) -> list:
124|         """Return a list of a column's data (date)."""
125|         def convert (txt) -> datetime:
126|             if txt[0:4].isnumeric():
127|                 return datetime.strptime(txt, '%Y-%m-%d')
128|             return ConvertDate(txt)
129|         # Detect and convert "Monday Jul 4" and "2026-07-04" date formats...
130|         ix = self.get_column_index(column_name)
131|         if reverse:
132|             return [convert(row[ix].strip()) for row in reversed(self)]
133|         else:
134|             return [convert(row[ix].strip()) for row in self]
135| 
136| 
137| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
138| class CsvMlbSeason (CsvBaseballData):
139|     """MLB Teams Season. (How each team did that season.)"""
140|     Filename = path.join(DataPath, '{year}', 'mlb-teams.csv')
141| 
142|     def __init__ (self, year=DefaultYear):
143|         super().__init__(self.Filename.format(year=year))
144| 
145| 
146| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
147| class CsvTeamGames (CsvBaseballData):
148|     """Game logs for the year, general."""
149|     Filename = path.join(DataPath, '{year}', 'games-{team}.csv')
150| 
151|     def __init__ (self, team_code=TwinsCode, team_year=DefaultYear):
152|         super().__init__(self.Filename.format(team=team_code, year=team_year))
153|         self.team_code = team_code
154|         self.team_year = team_year
155| 
156| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
157| class CsvTeamGamesBatting (CsvBaseballData):
158|     """Game logs for the year, batting."""
159|     Filename = path.join(DataPath, '{year}', 'games-{team}-batting.csv')
160| 
161|     def __init__ (self, team_code=TwinsCode, team_year=DefaultYear):
162|         super().__init__(self.Filename.format(team=team_code, year=team_year))
163| 
164| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
165| class CsvTeamGamesPitching (CsvBaseballData):
166|     """Game logs for the year, pitching."""
167|     Filename = path.join(DataPath, '{year}', 'games-{team}-pitching.csv')
168| 
169|     def __init__ (self, team_code=TwinsCode, team_year=DefaultYear):
170|         super().__init__(self.Filename.format(team=team_code, year=team_year))
171| 
172| 
173| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
174| class CsvTeamSeasons (CsvBaseballData):
175|     """Team Seasons. (all seasons)"""
176|     Filename = path.join(DataPath, 'seasons-{team}.csv')
177| 
178|     def __init__ (self, team_code=TwinsCode):
179|         super().__init__(self.Filename.format(team=team_code))
180| 
181| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
182| class CsvTeamSeasonsBatting (CsvBaseballData):
183|     """Team Seasons Batting. (all seasons)"""
184|     Filename = path.join(DataPath, 'seasons-{team}-batting.csv')
185| 
186|     def __init__ (self, team_code=TwinsCode):
187|         super().__init__(self.Filename.format(team=team_code))
188| 
189| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
190| class CsvTeamSeasonsPitching (CsvBaseballData):
191|     """Team Seasons Pitching. (all seasons)"""
192|     Filename = path.join(DataPath, 'seasons-{team}-pitching.csv')
193| 
194|     def __init__ (self, team_code=TwinsCode):
195|         super().__init__(self.Filename.format(team=team_code))
196| 
197| 
198| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
199| class CsvMlbSeasonsBatting (CsvBaseballData):
200|     """MLB Seasons Batting. All teams, all seasons."""
201|     Filename = path.join(DataPath, 'mlb-batting.csv')
202| 
203|     def __init__ (self):
204|         super().__init__(self.Filename)
205| 
206| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
207| class CsvMlbSeasonsPitching (CsvBaseballData):
208|     """MLB Seasons Pitching. All teams, all seasons."""
209|     Filename = path.join(DataPath, 'mlb-pitching.csv')
210| 
211|     def __init__ (self):
212|         super().__init__(self.Filename)
213| 
214| 
215| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
216| class ringbuff (list):
217|     """Simple ring buffer class (subclass of list)."""
218| 
219|     def __init__ (self, content, size=None):
220|         """Initialize new instance."""
221|         if content is None:
222|             list_items = []
223|         else:
224|             try:
225|                 list_items = list(content)
226|             except:
227|                 raise TypeError(f'Content for queue must be iterable, not {typename(content)}')
228| 
229|         if size is None:
230|             self._size = len(list_items)
231|             if self._size == 0:
232|                 raise ValueError(f'No queue content and no queue size.')
233|         else:
234|             self._size = size
235|             if self._size < len(list_items):
236|                 del list_items[:-self._size]
237| 
238|         # Initialize the list...
239|         super().__init__(list_items)
240| 
241|     def put (self, item):
242|         """Add an item to the tail of the buffer."""
243|         while self.size <= len(self):
244|             self.pop(0)
245|         self.append(item)
246| 
247|     def get (self):
248|         """Get an item from the head of the buffer."""
249|         if 0 < len(self):
250|             return self.pop(0)
251|         return None
252| 
253|     @property
254|     def size (self): return self._size
255| 
256|     def __str__ (self):
257|         """Return a print string version of the object."""
258|         items = [str(x) for x in self]
259|         return f'[{",".join(items)}]'
260| 
261|     def __repr__ (self):
262|         """Return a debug string version of the object."""
263|         return f'<{type(self).__name__} size={len(self)} @{id(self):012x}>'
264| 
265| 
266| 
267| ##================================================================================================##
268| """Round an integer (N) up/down to nearest boundary (sep)."""
269| 
270| RoundUp = lambda N,sep: int(((N//sep)+1)*sep)
271| RoundDown = lambda N,sep: int(((N//sep)+0)*sep)
272| 
273| ##================================================================================================##
274| def prn (s:str='', file=None) -> None:
275|     """Print string to Log, stdout, and (optionally) a file."""
276| 
277|     # Print the string to the log...
278|     Log.info(s)
279| 
280|     # Print the string to STDOUT...
281|     print(s)
282| 
283|     # Print the string to a file (optional)...
284|     if file:
285|         print(s, file=file)
286| 
287| ##================================================================================================##
288| def ConvertDate (date_string:str, date_year:int=DefaultYear) -> datetime:
289|     """Convert string like "Sunday Oct 19" to date object."""
290| 
291|     # Split into two parts on the first space...
292|     parts = date_string.partition(' ')
293| 
294|     # Check for parenthesized tail (index for double-headers)...
295|     if parts[2].endswith(')'):
296|         dtstr = parts[2].split('(')[0].strip()
297|     else:
298|         dtstr = parts[2].strip()
299| 
300|     # Parse and return a date object...
301|     return datetime.strptime(f'{dtstr} {date_year}', '%b %d %Y')
302| 
303| 
304| ##------------------------------------------------------------------------------------------------##
305| FileDumpCSS = """\
305| body {
305|     background-color: white;
305|     color: black;
305|     font-family: "Verdana", "Arial", "Helvetica", sans-serif;
305|     font-size: 9pt;
305|     font-weight: normal;
305|     font-style: normal;
305|     line-height: 1.25;
305|     text-decoration: none;
305|     text-align: left;
305|     vertical-align: bottom;
305|     padding: 0;
305|     border: 0;
305|     margin: 0;
305| }
305| 
305| h1, h2, h3, h4, h5, h6 {
305|     font-family: "Tahoma", "Verdana", "Arial", "Helvetica", sans-serif;
305|     font-weight: bold;
305|     font-style: normal;
305|     line-height: 1.0;
305|     text-decoration: none;
305|     text-align: left;
305|     vertical-align: top;
305|     padding: 0;
305|     border: 0;
305|     margin: 0;
305| }
305| h1 {color: #000000; font-size: 10pt; font-weight: normal; font-style: italic; text-align: right;}
305| h2 {color: #000000; font-size: 14pt; text-align: right;}
305| h3 {color: #603018; font-size: 12pt; text-align: left; margin-bottom: 9pt;}
305| h4 {color: #804020; font-size: small;}
305| h5 {color: #a05028; font-size: small;}
305| h6 {color: #183060; font-size: small; font-style: italic;}
305| table {
305|     font-size: 9px;
305|     border-spacing: 0;
305|     padding: 0;
305|     border: 0;
305|     margin: 6pt 9pt;
305| }
305| table thead th, tfoot th {
305|     background-color: navy;
305|     color: yellow;
305|     white-space: nowrap;
305|     text-align: center;
305|     vertical-align: middle;
305|     padding: 2px;
305|     border: 0;
305| }
305| table tbody td {
305|     background-color: white;
305|     color: black;
305|     white-space: nowrap;
305|     text-align: left;
305|     vertical-align: bottom;
305|     padding: 2px 3px 3px 2px;
305|     border-right: 1px solid #7f7f7f;
305|     border-bottom: 1px solid #7f7f7f;
305| }
305| table tbody .Number {text-align:right;}
305| table tbody .LineLeft {border-left:1px solid #7f7f7f;}
305| """

306| 
307| ##================================================================================================##
308| def do_csv_file_dump (**kwargs):
309|     """CMND: Dump a specified file's contents to log and stdout."""
310|     fpath = KWARG('fpath', ListPath, str, kwargs)
311|     fname = KWARG('fname', 'csv-{cname}.html', str, kwargs)
312|     cname = KWARG('class', 'MlbSeason', str, kwargs)
313|     tcode = KWARG('team', TwinsCode, str, kwargs)
314|     year  = KWARG('year', DefaultYear, int, kwargs)
315|     file_name = path.join(fpath,fname) if fpath else fname
316|     file_name = file_name.format(**locals())
317|     Log.info(f'csv-file-dump:: {list(kwargs.keys())}')
318|     Log.debug(f'{fpath=}')
319|     Log.debug(f'{fname=}')
320|     Log.debug(f'{cname=}')
321|     Log.debug(f'{tcode=}')
322|     Log.debug(f'{year=}')
323|     Log.debug(f'{file_name=}')
324|     Log.info()
325|     #TODO: Use tcode and year when appropriate.
326| 
327|     # Get the globals...
328|     gs = globals()
329|     cn = f'Csv{cname}'
330|     if cn not in gs:
331|         raise ValueError(f'Oops! Unknown class name: {cn}')
332| 
333|     # Get the class and create a new instance...
334|     cls = gs[cn]
335|     obj = cls()
336|     prn(f'{obj.filename} ({len(obj)} lines, {obj.fsize} bytes)')
337|     prn()
338| 
339|     # Create webpage object...
340|     props = dict(
341|         h1 = f'Baseball',
342|         h2 = f'CSV Data File',
343|         h3 = f'{cname}',
344|         css = ['https://sonnack.com/basic.css'],
345|         csstxt = FileDumpCSS,
346|     )
347|     pg = WebPage(f'CSV:{cname}', **props)
348| 
349|     # Header...
350|     pg.add('<table>')
351|     pg.add('<thead><tr>')
352|     for col_name in obj.hdrs:
353|         pg.add(f'<th>{col_name}</th>')
354|     pg.add('</tr></thead>')
355| 
356|     # Footer...
357|     pg.add('<tfoot><tr>')
358|     for col_name in obj.hdrs:
359|         pg.add(f'<th>{col_name}</th>')
360|     pg.add('</tr></tfoot>')
361| 
362|     def is_a_number (s):
363|         """See if s is a number."""
364|         for ch in s:
365|             if ch not in '-+.0123456789':
366|                 return False
367|         return True
368| 
369|     # Data...
370|     pg.add('<tbody>')
371|     for row in obj:
372|         pg.add('<tr>')
373|         for ix,col in enumerate(row):
374|             left = ' LineLeft' if ix==0 else ''
375|             if is_a_number(col):
376|                 pg.add(f'<td class="Number {left}">{col}</td>')
377|             else:
378|                 pg.add(f'<td class="{left}">{col}</td>')
379|         pg.add('</tr>')
380|     pg.add('</tbody>')
381|     pg.add('</table>')
382| 
383|     # Save the webpage...
384|     pg.save(file_name, log=Log)
385| 
386|     Log.info()
387|     return file_name
388| 
389| ##================================================================================================##
390| def do_test_csv (**kwargs):
391|     """CMND: Exercise the CSV classes."""
392|     fpath = KWARG('fpath', ListPath, str, kwargs)
393|     fname = KWARG('fname', 'csv-test.out', str, kwargs)
394|     Log.info(f'csv-exercise:: {list(kwargs.keys())}')
395|     Log.debug(f'{fpath=}')
396|     Log.debug(f'{fname=}')
397|     Log.info()
398| 
399|     def log_and_print (obj, fp):
400|         """Emit properties, headers, and first two data rows of CSV object."""
401| 
402|         prn(getattr(obj, 'Filename', '<none>'), file=fp)
403|         prn(f'{obj.filename} ({len(obj)} lines, {obj.fsize} bytes)', file=fp)
404|         prn(obj.hdrs, file=fp)
405|         prn(obj[0], file=fp)
406|         prn(obj[1], file=fp)
407|         prn(file=fp)
408| 
409|     fn = path.join(fpath,fname) if fpath else fname
410|     fp = open(fn, mode='w', encoding='utf-8')
411|     try:
412|         log_and_print(CsvBaseballData(path.join(DataPath, 'mlb-batting.csv')), fp)
413|         log_and_print(CsvMlbSeason(), fp)
414|         log_and_print(CsvTeamGames(), fp)
415|         log_and_print(CsvTeamGamesBatting(), fp)
416|         log_and_print(CsvTeamGamesPitching(), fp)
417|         log_and_print(CsvTeamSeasons(), fp)
418|         log_and_print(CsvTeamSeasonsBatting(), fp)
419|         log_and_print(CsvTeamSeasonsPitching(), fp)
420|         log_and_print(CsvMlbSeasonsBatting(), fp)
421|         log_and_print(CsvMlbSeasonsPitching(), fp)
422| 
423|     except:
424|         raise
425| 
426|     finally:
427|         fp.close()
428| 
429|     Log.info()
430|     return f'wrote: {fn}'
431| 
432| ##================================================================================================##
433| def do_test (**kwargs):
434|     """CMND: Do a test."""
435|     fpath = KWARG('fpath', BasePath, str, kwargs)
436|     fname = KWARG('fname', 'test-{tcode}-{year}.png', str, kwargs)
437|     tcode = KWARG('team', TwinsCode, str, kwargs)
438|     year  = KWARG('year', DefaultYear, int, kwargs)
439|     team_name = MlbTeams[tcode][2]
440|     file_name = path.join(fpath,fname) if fpath else fname
441|     file_name = file_name.format(**locals())
442|     Log.info(f'test:: {list(kwargs.keys())}')
443|     Log.debug(f'{fpath=}')
444|     Log.debug(f'{fname=}')
445|     Log.debug(f'{tcode=}')
446|     Log.debug(f'{year=}')
447|     Log.debug(f'{team_name=}')
448|     Log.debug(f'{file_name=}')
449|     Log.info()
450| 
451|     # Extract data from team's season...
452|     csv_data = CsvTeamGames(tcode)
453| 
454|     Log.info()
455|     return file_name
456| ####################################################################################################
457| def dispatch (cmd, **kwargs):
458|     """Dispatch to a module function based on CMD."""
459|     Log.info(f'CMD: {cmd}')
460|     for kw in kwargs:
461|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
462|     Log.info()
463| 
464|     if cmd == 'dmp':  return do_csv_file_dump   (**kwargs)
465|     if cmd == 'csv':  return do_test_csv        (**kwargs)
466|     if cmd == 'test': return do_test            (**kwargs)
467| 
468|     return 'Nothing to do!'
469| ####################################################################################################
470| if __name__ == '__main__':
471|     print(f'autorun: {argv[0]}')
472|     Log.start(path.join(BasePath,'defs.log'))
473|     Log.level(info())
474|     Log.info(argv[0])
475|     cmd = argv[1] if 1 < len(argv) else CMND
476|     kwargs = ARGS
477|     for a in argv[2:]:
478|         nv = a.split('=', 1)
479|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
480|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
481|     Log.info()
482|     try:
483|         print(f'CMD: {cmd}')
484|         print()
485|         obj = dispatch(cmd, **kwargs)
486|         print(obj)
487|         print()
488|         Log.info(obj)
489|         Log.info()
490|     except:
491|         etype, evalue, tb = exc_info()
492|         ts = extract_tb(tb)
493|         Log.error()
494|         Log.error(f'{etype.__name__}: {evalue!s}')
495|         Log.error()
496|         for t in ts[-5:]:
497|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
498|             Log.error(f' {t[3]}')
499|             Log.error()
500|         raise
501|     finally:
502|         Log.end()
503| ####################################################################################################
504| """eof"""
505|