Ejemplo n.º 1
0
def main():
    """ Hooray, a giant if-elif-else tree!
    """
    # TODO:     1. move ALL this junk to main(), call from here
    #           2. open shelve file here
    #           3. check to see if there IS a current response key
    #           4. put open/close shelve in update so it can be called
    #              seperately
    # -------------------------------------------------------------------------
    # init variables
    # -------------------------------------------------------------------------
    home_dir = '/usr/self/weather'
    # here we make sure the package imports can go through:
    if home_dir not in sys.path:
        sys.path.append(home_dir)
    import config.loaders
    import logging
    import utils.utilities as utils
    config_file = config.loaders.config_file_name()
    weather_db_name = config.loaders.day_file_name()
    log_file = config.loaders.log_file_name()
    logging.basicConfig(filename=log_file, level=logging.DEBUG,
        format="%(levelname)s:%(name)s:%(asctime)s -- %(message)s")

    args = parse_arguments()
    logging.debug("Loaded args object. {} attrs in args.__dict__".format(
        len(args.__dict__)))

    configs = config.loaders.parse_config()
    loop_flag = True
    while loop_flag is True:
        try:
            if args.update:
                args.verbose = True
                update(verbose=args.verbose, check_time=True)
                loop_flag = False
            elif args.options:
                temp = config.loaders.load_vars(config_file)
                res = config.loaders.key_formatter(temp)
                for r in res:
                    print(r)
                loop_flag = False
            else:
                # only get current response object if we need it
                import returner
                current = returner.main()

                if args.width:
                    screen_width = min(utils.get_terminal_width(), args.width)
                else:
                    screen_width = utils.get_terminal_width()
                if args.logging:
                    logging.info("Sending test message -- all is well!")
                    loop_flag = False
                elif args.debug in ['current', 'c']:
                    res = config.loaders.key_formatter(
                        current['current_observation'])
                    for r in res:
                        print(r)
                    loop_flag = False
                elif args.debug in ['hourly', 'h']:
                    res = config.loaders.key_formatter(
                        current['hourly_forecast'][0])
                    for r in res:
                        print(r)
                    loop_flag = False
                elif args.debug in ['forecast', 'f']:
                    res = config.loaders.key_formatter(
                        current['forecast']
                               ['simpleforecast']
                               ['forecastday'][0])
                    for r in res:
                        print(r)
                    loop_flag = False
                elif args.files:
                    raise NotImplementedError
                elif args.yesterday:
                    import printers.prinutils as pu
                    import utils.file_utils as fu
                    import datetime as dt
                    tim = dt.date.today() - dt.timedelta(days=1)
                    target = config.loaders.day_file_name(tim)
                    target_keys = []
                    target_keys.append(('current_observation', 'temp_f'))
                    target_keys.append(('current_observation',
                                        'observation_epoch'))

                    opened = fu.parse_database(target, target_keys)
                    res = pu.day_temps_formatter(opened[target_keys[0]],
                                                 opened[target_keys[1]])
                    print("Queried Temperatures for {}".format(
                        tim.strftime('%b %d %y')))
                    for lin in res:
                        print(lin)
                elif args.moon:
                    import printers.moon
                    printers.moon.print_moon(current['moon_phase'])
                    loop_flag = False
                elif (args.keys or args.recent or args.query or args.times):
                    print_bookkeeping(args, current_ob=current,
                                      weat_db=weather_db_name)
                    loop_flag = False
                elif args.now or not (args.hourly or args.forecast):
                    import printers.current
                    printers.current.print_current(
                        current['current_observation'], args)
                    loop_flag = False
                elif args.hourly:
                    import printers.print_hourly
                    res = printers.print_hourly.print_hourly(
                        current['hourly_forecast'],
                        current['sun_phase'],
                        configs,
                        screen_width)
                    for lin in res:
                        print(lin)
                    loop_flag = False
                elif args.forecast:
                    #  print('args.forecst: {}'.format(args.forecast))
                    #  if args.forecast.startswith('w'):
                    if args.forecast[0].startswith('w'):
                        frmt = 'week'
                    elif args.forecast[0].startswith('g'):
                        frmt = 'grid'
                    else:
                        # the default, should be set in a config file
                        frmt = 'grid'
                    import printers.forecast
                    res = printers.forecast.print_forecast(
                        current['forecast']
                               ['simpleforecast']
                               ['forecastday'],
                        frmt=frmt,
                        screen_width=screen_width)
                    for lin in res:
                        print(lin)
                    loop_flag = False
            # if we've fallen through to here, do SOMETHING useful:
            if loop_flag is not False:
                update(verbose=args.verbose)
                loop_flag = False
        except KeyError as e:
            # update(verbose=args.verbose)
            message = "KeyError caught: {}".format(e)
            print(message)
            import traceback
            traceback.print_exception(*sys.exc_info())
            loop_flag = False
            logging.debug(message)
        except Exception as e:
            # tb = sys.exc_info()[2]
            message = "exception caught at top level: {}".format(e)
            print(message)
            import traceback
            traceback.print_exception(*sys.exc_info())
            loop_flag = False
            logging.debug(message)