Run.py - это сценарий для инициализации вычислений, вызывающий функцию из dbm_utilities.py. Data_input.py - это сценарий, который необходимо выполнить в dbm_utilities.py, чтобы получить набор данных для расчета.
Как мы можем просто выполнить Run.py и получить результаты?
Как разрешить Data_input.py запускаться внутри dbm_utilities.py на основе идентификатора студента и других переменных, представленных в Run.py?
Мне просто нужны некоторые рекомендации и предложения о том, как интегрировать два моих маленьких скрипта (Run.py и Data_input.py) с dbm_utilities.py. Спасибо.
# Run.py - the top layer that get results from dbm_utilities.py
from __future__ import (absolute_import, division, print_function)
unicode = type(u' ')
import warnings
import sys
if __name__ == '__main__':
if not sys.warnoptions:
warnings.simplefilter("ignore")
# STEP 1: Testing condition
try:
print('\nLoading testing condition ...')
quanity = 100.
adjust = 0.2
except RuntimeError:
print('\nTesting condition is not parameterized.')
else:
print('\nDone!')
# STEP: Student ID
try:
print('\nLoading student ID ...')
ID = 'Michael'
except RuntimeError:
print('\nStudent ID is not parameterized.')
else:
print('\nDone!')
# Run the calculation
try:
print('\nImporting calculation results ...')
ID, Adjusted_AveScore = dbm_utilities.get_report(ID, quanity, adjust)
print("Student Name:")
print(ID)
print("The score after adjustment:")
print(Adjusted_AveScore)
except RuntimeError:
print('\nModel is not running.')
else:
print('\nDone')
Run.py предоставляет параметры и идентификатор студента, а затем вызывает dbm_utilities.get_report, чтобы получить окончательный скорректированный результат.
# dbm_utilities.py - the middle layer that do the calculation
from __future__ import (absolute_import, division, print_function)
# Get the ID, quanity, adjust from Run.py
def get_report(ID, quanity, adjust):
if isinstance(substance, str) or isinstance(substance, unicode):
ID, AveScore, Adjusted_AveScore = get_the_average(ID, adjust)
if quanity < 100:
print("Warning: student number is less than 100.")
return (ID, Adjusted_AveScore)
# --- Utilities ---
def get_the_average(ID, adjust):
AveScore = (Math + English + French + Sports) / 4.0
Adjusted_AveScore = AveScore * adjust
return (ID, AveScore, Adjusted_AveScore)
dbm_utilities.py получает идентификатор студента и параметры из Run.py для вычислений, а затем возвращают результаты обратно в Run.py.
# Data_input.py - the lower layer to extract data from a database
# TODO: Get the ID from dbm_utillities.py
# For example:
# ID = "Michael"
with open("./Scores.txt", 'r') as infile:
text = infile.read().strip().split('\n')
header = text[0].split()[1:]
rows = [row.split() for row in text[1:]]
score_lib = {row[0]: [r for r in row[1:]] for row in rows}
def Math(ID):
Math = (score_lib[ID][header.index("Math")])
return float(Math)
def English(ID):
English = (score_lib[ID][header.index("English")])
return float(English)
def French(ID):
French = (score_lib[ID][header.index("French")])
return float(French)
def Sports(ID):
Sports = (score_lib[ID][header.index("Sports")])
return float(Sports)
Math = Math(ID)
English = English(ID)
French = French(ID)
Sports = Sports(ID)
Data_input.py - это сценарий, который считывает набор данных и извлекает данные на основе идентификатора студента. Идентификатор студента предоставляется в Run.py.
Вот набор данных:
ID Math English French Sports
Michael 100.0 57.0 73.0 90.0
Nancy 90.0 66.0 91.0 85.0
Eva 95.0 92.0 83.0 91.0
George 64.0 47.0 71.0 67.0
Emma 87.0 74.0 59.0 88.0
Сценарии и набор данных можно скачать по адресу https://www.dropbox.com/sh/id22danjnq6gobk/AAASf5e1mCJQPKB4z9bcg_ILa?dl=0