troubleshooting Question

Building a python class and calling it from outside the class

Avatar of sara_bellum
sara_bellumFlag for United States of America asked on
Python
13 Comments3 Solutions384 ViewsLast Modified:
I have a script that uses nested dictionaries to order station headers and links to station files on an html page. The new requirement is to color the links based on whether the links point to empty or populated graphs. I tried writing a loop to dynamically assign link colors to the files, but nested dictionaries do not lend themselves to this (at least I haven't found a way to make it work).

So I thought to build a class instead, where file attributes can be assigned dynamically, I think. But I have little to no experience with classes; rewriting functions into class methods and calling them outside the context of scripted examples looks next to impossible. Maybe it is for the moment, but I'll start with these questions:

a) All the variables used by the class should be defined by the init method, but some return undefined errors - why?
b) How does one call a class or method from outside the class? With lots of trial and error, my attempts fail with attribute or undefined errors.
c) Is it possible to process an ini file in the way I attempt below, i.e., take the paths to station log files and pass them to the class?




[Main]
base_dir = /home/user1/public_html/stations/
www_base = /stations/
template_file = /home/user2/cron/graphs/template.html
destination = /home/user2/public_html/stations/graphs.html
contact_address = user3@website.com
network_url = http://web-stations.org

[Stations]
stn1 = Station 1
stn2 = Station 2
stn3 = Station 3
etc...

[Graphs]
diag = Diagnostics
air = Air Temperature
bar = Barometric Pressure
etc...

Open in new window

import os, sys
import time
from datetime import datetime, date, timedelta
import pytz
import fileinput
import ConfigParser
from configobj import ConfigObj

try:
    cfg = sys.argv[1]
except:
    print 'Error: pls include config file!'
    sys.exit()

parser = ConfigParser.SafeConfigParser()
parser.read(cfg)
destination = parser.get('Main', 'destination')
network_url = parser.get('Main', 'network_url')
source_dir = parser.get('Main', 'source_dir')
target = open(destination, 'w')

station_list = [ 'stn1', 'stn2', 'stn3', 'stn4', 'stn5', \
                 'stn6', 'stn7', 'stn8', 'stn9', 'stn10' ]


class SourceError(Exception): 
    log = "Sorry, no source logs were found"


class Station:

    def __init__(self, source, option):
        self.source = source
        self.option = option
    
        self.current_date = current_date
    
        self.InDiag = InDiag
        self.line_list = line_list
        self.last_line = last_line
        self.last_ts = last_ts
        self.ts = ts
        self.time_diff = time_diff
        
        self.station_list = station_list
        self.period_list = period_list
        self.link_colors = link_colors
        self.result = result

    def procIni(self, source, option):
        
        print 'option', option   
        
        InDiag = open(self.source, 'r')
        line_list = InDiag.readlines()
        last_line = line_list[len(line_list)-1]
        last_ts = last_line[1:20]
        (rYr, rMo, rDay, rHr, rMin, rSec) = time.strptime(last_ts, "%Y-%m-%d %H:%M:%S")[0:6]
        ts = datetime(rYr, rMo, rDay, rHr, rMin, rSec, tzinfo=pytz.timezone('America/Anchorage'))
        time_diff = current_date - ts
        
        print 'time_diff', time_diff
        
        for stn in station_list:
            if option == stn:
                if float(time_diff.days) == -1:
                    delay = 0
                else:
                    delay = float(time_diff.days)
                    delay = int(round(delay, 0)

                return stn, delay
    
    def procStns(stn, delay):
        
        period_list = [ 7, 14, 30, 60, 120, 180, 360 ]
        link_colors = [ 'red', 'blue' ]
        
        for period in period_list:
            result = delay - period
            
         # process station files to figure out which results are 
         # positive and negative, find the highest negative 
         # result for each time increment by station,
         # then assign link colors to the 
         # file links based on the numbers

     
if __name__ == '__main__' :
    
    config = ConfigObj(cfg)
    current_date = datetime.now(pytz.timezone('America/Anchorage'))
    
    for option in config['Stations']:
        
        diag_path = source_dir + option + '/' + option
        if option in [ 'stn1', 'stn2', 'stn3' ]:
            source = diag_path + '_diag.dat'
        elif option == 'stn4':
            source = diag_path + '_diagnotics.dat'
        else:
            source = diag_path + '_hourlydiag.dat'
            
            if source: 
                
                try: 
                    Station(source, option)
                except SourceError:
                    print SourceError.log

Open in new window

ASKER CERTIFIED SOLUTION
pepr

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 3 Answers and 13 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 3 Answers and 13 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros