[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...
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
ASKER
ASKER
class PrintMe:
def __init__(self, speech, number, value):
self.speech = 'War'
self.number = number
self.value = value
def __words__(self, speech):
speech = speech.upper(speech + ' and Peace')
return speech
def __add__(self, number, value):
my_sum = number + value
return my_sum
x = PrintMe('words', 3, 4)
#print 'x = ', x.my_sum # my sum not defined (not in init method)
#y = PrintMe(speech) # AttributeError:
#PrintMe instance has no attribute 'speech' and speech is not defined
y = PrintMe('look for quoted text', 3, 4)
print 'this prints only init value:', y.speech
ASKER
class Adder:
def __init__(self, number, value): # when does init() need args?
self.number = number
self.value = value
self.my_sum = my_sum
def add(self, number, value): # method has args
self.my_sum = number + value
return my_sum
x = Adder(3, 4) # does the class need args?
x.add(3, 4) # the method needs args!
print x.my_sum # NameError: global name 'my_sum' is not defined
ASKER
class Adder:
def __init__(self, number, value, my_sum):
# does init() always need args to define variables?
self.number = number
self.value = value
self.my_sum = my_sum
def add(self, number, value):
self.my_sum = number + value # why self.my_sum and not my_sum?
#return my_sum # NameError: global name 'my_sum' is not defined. Why?
x = Adder(1, 2, 3) # the class needs args to serve as placeholders
x.add(3, 4) # the method args are not read unless they're fed to init()
print x.my_sum # prints 7
ASKER
Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.
TRUSTED BY
"a) All the variables used by the class should be defined by the init method, but some return undefined errors - why?"
This is only a recommendation. The instance variables can be created on-the-fly. What errors do you mean? Is there any special reason to use the non-standard configobj module?
"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."
A class is the description of the data structure and the code that works with the data. The class definition is static. When you want to use it, you usually create an instance of that class -- also known as "the object" of the class. Basically, it contains the data part of the wanted "something" plus reference to the class that defines the code. It makes no sense to say to "call a class or a method from outside a class". You are always calling a code. The code can be part of the class definition. You can call the code via the class name; however, it is mostly called via the object instance. If Station is you class, then "calling"
Station(source, option)
... actually mean creating the object (the instance of the class). You most probably want to keep the reference to the created object and then you want to use that object. Using the object often means to call its methods.
station = Station(source, option)
station.procIni() # this should probably be called by the __init__()
station.procXxx()
"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?"
There is nothing magical related to the classes. They (roughly said) define what data may be used "from inside" and what code belongs to the class. The code usually manipulates with the passed arguments and with the variables (usually with the object variables).
I am planning to write the sequels to the http:A_5354-Python-basics-illustrated-part-1.html article where the things are to be explained. Until then, ask for details here. It may be valuable for both you and me ;) (I will use your questions in the article to keep myself in pace with beginners).