PyScore

001: #! /usr/bin/python
002: ######## pyscore.py ######## python package PyScore main module ########
003: 
004: # PyScore
005: # a race scoring programme
006: # written by Matt Draisey
007: # 2004 April 6
008: 
009: ######## pyscore.py ######## python package PyScore main module ########
010: 
011: import datetime,optparse,os,sys
012: import re
013: 
014: ######## ######## set up command line parser ######## ########
015: 
016: cmds=["initialize","register","timesheet","tabulate","scrape","sniff"]
017: 
018: clp=optparse.OptionParser(
019:     usage="usage: %prog [options] ("+"|".join(cmds)+") ...",
020:     version="%prog 0.0.1",
021: )
022: clp.add_option("-v","--verbose",action="count",help="set verbose output")
023: clp.add_option("-f","--file",help="specify configuration file")
024: clp.add_option("-y","--yaml",help="specify boat configuration data file")
025: (opts,args)=clp.parse_args()
026: 
027: ######## ######## read options and command operation ######## ########
028: 
029: ######## ######## set verbosity ######## ########
030: 
031: from utility.verbose import verbosity
032: verbosity(opts.verbose)
033: from utility.verbose import v,vv,vvv
034: 
035: ######## ######## set up the conf file specified in argv ######## ########
036: 
037: from utility import cmdline
038: 
039: try:
040:     if opts.file<>None:
041:         confdir=os.path.dirname(os.path.normpath(opts.file))
042:         confdir=confdir or "."
043:         conffile=file(opts.file,"rU")
044:         print>>v,"LOADING CONFIGURATION:",opts.file
045:     else:
046:         try:
047:             cmdline.has_suffix(args[0],"conf.pysc","conf.pyscore")
048:             confdir=os.path.dirname(os.path.normpath(args[0]))
049:             confdir=confdir or "."
050:             conffile=file(args[0],"rU")
051:             print>>v,"LOADING CONFIGURATION:",args[0]
052:             del args[0]
053:         except (IndexError,IOError):
054:             confdir="."
055:             conffile=file("conf.pyscore","rU")
056:             print>>v,"LOADING CONFIGURATION: conf.pyscore"
057: except IOError:
058:     confdir="."
059:     print>>v,"NO CONFIGURATION LOADED"
060: else:
061:     try:
062:         exec conffile
063:         print>>v,"CONFIGURATION LOADED SUCESSFULLY"
064:         print>>v
065:     finally:
066:         conffile.close()
067: 
068: ######## ######## get operation from argv ######## ########
069: 
070: try:
071:     operation=cmdline.CommandAbbreviations(cmds).command_lookup(args[0])
072:     print>>v,"EXPLICIT OPERATION SPECIFIED:",operation
073:     del args[0]
074: except (IndexError,KeyError):
075:     try: assert isinstance(operation,str)
076:     except NameError:
077:         operation=""
078:         print>>v,"NO OPERATION SPECIFIED"
079:         clp.print_usage()
080:     else: print>>v,"DEFAULT OPERATION SPECIFIED:",operation
081: 
082: ######## ######## ######## common subroutines ######## ######## ######## 
083: 
084: def yield_boatconf_yaml_file(write=False):
085:     try:
086:         if opts.yaml<>None:
087:             y=opts.yaml
088:         else:
089:             try: assert isinstance(boatconf_yaml,str)
090:             except NameError:
091:                 y=args[0]
092:                 cmdline.has_suffix(y,"boatconf.yaml")
093:                 del args[0]
094:             else: y=os.path.join(confdir,boatconf_yaml)
095:     except IndexError:
096:         print>>v,"BOATCONF FILE NOT SPECIFIED"
097:     else:
098:         if write:
099:             try:
100:                 boatfile=file(y,"r+")
101:                 print>>v,"OPENING BOATCONF:",y
102:             except IOError:
103:                 defaulty="test.pyscore.boatconf.yaml"
104:                 boatfile=file(defaulty,"w+")
105:                 print>>v,"OPENING DEFAULT BOATCONF:",defaulty
106:             yield boatfile
107:         else:
108:             try:
109:                 boatfile=file(y,"rU")
110:                 print>>v,"READING BOATCONF:",y
111:                 yield boatfile
112:             except IOError:
113:                 print>>v,"BOATCONF FILE NOT FOUND"
114: 
115: def call_with_boatconf_yaml_file(action,write=False):
116:     for boatfile in yield_boatconf_yaml_file(write):
117:         try:
118:             action(boatfile)
119:         finally:
120:             boatfile.close()
121: 
122: def timesheet_log_file(write=False):
123:     try:
124:         try:
125:             cmdline.has_suffix(args[0],"timesheet.log")
126:             y=args[0]
127:             del args[0]
128:             print>>v,"OPENING EXPLICIT TIMESHEET: %s"%y
129:         except IndexError:
130:             try: assert isinstance(timesheet_log,str)
131:             except NameError: raise IOError
132:             else: y=os.path.join(confdir,timesheet_log)
133:             print>>v,"OPENING DEFAULT TIMESHEET: %s"%y
134: 
135:         if write:
136:             try: datafile=file(y,"r+")
137:             except IOError: datafile=file(y,"w+")
138:         else: datafile=file(y,"rU")
139: 
140:         dataname=os.path.basename(y)
141:         if dataname.endswith(".timesheet.log"): dataname=dataname[:-14]
142:         elif dataname.endswith("timesheet.log"): dataname=dataname[:-13]
143:         print>>v,"TIMESHEET NAME: %s"%dataname
144: 
145:     except IOError:
146:         datafile=file("test.pyscore.timesheet.log","w+")
147:         dataname="test.pyscore"
148:         print>>v,"WRITING TEST TIMESHEET: test.pyscore.timesheet.log"
149:         print>>v,"TIMESHEET NAME: test.pyscore"
150: 
151:     return datafile,dataname
152: 
153: ######## ######## ######## the operations ######## ######## ######## 
154: 
155: if operation=="initialize":
156: 
157:     from standing import boatinit
158:     call_with_boatconf_yaml_file(boatinit.dumpconf,write=True)
159:     #for boatfile in yield_boatconf_yaml_file(write=True):
160:     #    try:
161:     #        from standing import boatinit
162:     #        boatinit.dumpconf(boatfile)
163:     #    finally:
164:     #        boatfile.close()
165: 
166: elif operation=="register":
167: 
168:     # set up graphics libraries
169: 
170:     import pygtk
171:     pygtk.require('2.0')
172:     import gtk
173:     if sys.path[0].endswith("gtk-2.0"):
174:         sys.path[2:2]=[sys.path[0]]
175:         del sys.path[0]
176: 
177:     # set up the pickled config files specified in argv
178: 
179:     from standing import boatinit
180:     call_with_boatconf_yaml_file(boatinit.loadconf) #write=True
181:     #for boatfile in yield_boatconf_yaml_file(): #write=True
182:     #    try:
183:     #        from standing import boatinit
184:     #        boatinit.loadconf(boatfile)
185:     #    finally:
186:     #        boatfile.close()
187: 
188:     # set initial gui and run the programme
189: 
190:     import register
191:     register.registergui.window()
192:     gtk.main()
193: 
194: elif operation=="timesheet":
195: 
196:     # set up graphics libraries
197: 
198:     import pygtk
199:     pygtk.require('2.0')
200:     import gtk
201:     if sys.path[0].endswith("gtk-2.0"):
202:         sys.path[2:2]=[sys.path[0]]
203:         del sys.path[0]
204: 
205:     # load boat database
206: 
207:     from standing import boatinit
208:     call_with_boatconf_yaml_file(boatinit.populate)
209: 
210:     # today
211: 
212:     print>>v,"TODAY:",datetime.datetime.now()
213:     
214:     # set up the gui
215: 
216:     import timesheet
217: 
218:     # debug menu actions
219:     # simple interactive interpreter
220: 
221:     def on_reload():
222:         from utility import guiutils
223:         guiutils.reloader(timesheet,{})
224: 
225:     timesheet.gui.guiview.widgets.signal_autoconnect({
226:         "on_reload1_activate": lambda *x: on_reload(),
227:         "on_interact1_activate":
228:         lambda *x: code.interact("PyScore",local=globals()),
229:     })
230: 
231:     # the timesheet file
232: 
233: #    import timesheet.entries,\
234: #        timesheet.numbers,timesheet.boats,timesheet.finishes,timesheet.classes
235: 
236:     timesheet.entries.populate(*timesheet_log_file(write=True))
237: 
238:     # set initial gui and run the programme
239: 
240:     timesheet.gui.guiview.entrywindow.show()
241:     gtk.main()
242: 
243: elif operation=="tabulate":
244: 
245:     from tabulate import populate
246:     populate.populate(confdir)
247: 
248: elif operation=="scrape":
249: 
250:     def scraper(boatfile):
251:         try:
252:             from standing import scrapebase
253:             scrapings=scrapebase.ScrapeBase()
254:             scrapings.load_hierarchy(boatfile)
255:             scrapings.create_dictionaries()
256:         except (IOError,EOFError,ValueError):
257:             pass
258:         else:
259:             scrapings.import_all_timesheets(confdir)
260:             dumper=scrapings.scraping_hierarchy()
261:             #dumper.print_base()
262:             boatfile.seek(0)
263:             dumper.print_base(boatfile)
264:             boatfile.truncate()
265:     call_with_boatconf_yaml_file(scraper,write=True)
266: 
267: elif operation=="sniff":
268: 
269:     import csv
270:     from pprint import pprint
271:     pprint(csv.list_dialects())
272:     print "DIALECT DEFAULTS"
273:     pprint(csv.Dialect.__dict__)
274:     for d in csv.list_dialects():
275:         print "DIALECT:",d
276:         dialect = csv.get_dialect(d)
277:         pprint(dialect.__dict__)
278:         print "doublequote =",dialect.doublequote
279:         print "quotechar =",dialect.quotechar
280:     datafile,dataname=timesheet_log_file(write=False)
281:     sniff = csv.Sniffer().sniff
282:     pprint(sniff(datafile.next()).__dict__)
283: 
284:     pprint(map(None,csv.reader(datafile,skipinitialspace=True)))
285: 
286: ######## pyscore.py ######## python package PyScore main module ########