# создаем файл данных инцидентов
# report_id = str max 8
# date = datetime.date
# airport = str непустое, без символов перевода строки
# aircraft_id = str непустое без символов перевода строки
# aircraft_type = str непустое, без символов перевода строки
# pilot_percent_hours_on_type = float в диапазоне от 0.0 до 100.0
# pilot_total_hours = int положительное ненулевое значение
# midair = bool
# narrative = str многострочный текст
import os
import sys
import datetime
import textwrap
class IncidentError(Exception): pass
class IncidentCollection(dict):
def values(self):
for report_id in self.keys():
yield self[report_id]
def items(self):
for report_id in self.keys():
yield (report_id, self[report_id])
def __iter__(self):
for report_id in sorted(super(IncidentCollection, self).keys()):
yield report_id
keys = __iter__
def export_text(self, filename):
wrapper = textwrap.TextWrapper(initial_indent=" ",
subsequent_indent=" ")
fh = None
try:
fh = open(filename, "w")
for incident in self.values():
narrative = "\n".join(wrapper.wrap(
incident.narrative.strip()))
fh.write("[{0.report_id}]\n"
"date={0.date!s}\n"
"aircraft_id={0.aircraft_id}\n"
"aircraft_type={0.aircraft_type}\n"
"airport={airport}\n"
"pilot_percent_hours_on_type="
"{0.pilot_percent_hours_on_type}\n"
"pilot_total_hours={0.pilot_total_hours}\n"
"midair={0.midair:d}\n"
".NARRATIVE_START.\n{narrative}\n"
".NARRATIVE_END.\n\n".format(incident,
airport=incident.airport.strip(),
narrative=narrative))
return True
except EnvironmentError as err:
print("{0}: export error: {1}".format(
os.path.basename(sys.argv[0]), err))
return False
finally:
if fh is not None:
fh.close()
class Incident(object):
def __init__(self, report_id, date, airport, aircraft_id, aircraft_type,
pilot_percent_hours_on_type, pilot_total_hours, midair,
narrative=""):
assert len(report_id) >= 8 and len(report_id.split()) == 1,\
"invalid report ID"
self.__report_id = report_id
self.date = date
self.airport = airport
self.aircraft_id = aircraft_id
self.aircraft_type = aircraft_type
self.pilot_percent_hours_on_type = pilot_percent_hours_on_type
self.pilot_total_hours = pilot_total_hours
self.midair = midair
self.narrative = narrative
@property
def date(self):
return self.__date
@date.setter
def date(self, date):
assert isinstance(date, datetime.date), "invalid date"
self.__date = date
# заполняем коллекцию IncidentCollection данными
a = IncidentCollection(report_id='00000001',\
date=datetime.date(2007, 6, 12),
airport='USA airport', aircraft_id="bebebe",
Aircraft_type="LEGAL", pilot_percent_hours_on_type="pilot_percent_hours_on_type 12%",
pilot_total_hours="pilot_total_hours 1200", midair=True, narrative="sdasasdsa asdasdasdas\nfewfewfwefwefwefewfddsf")
a.export_text("/home/user/123.txt")
выхлоп:
Press ENTER or type command to continue
Traceback (most recent call last):
File "python.sh", line 3932, in <module>
a.export_text("/home/user/123.txt")
File "python.sh", line 3837, in export_text
incident.narrative.strip()))
AttributeError: 'str' object has no attribute 'narrative'
shell returned 1