Python - 调用多个函数(未解析的参考)。何时使用全局变量?

时间:2017-11-16 12:00:28

标签: python function

我刚刚开始学习函数并且我理解基础知识,但是我不理解如何在更复杂的脚本中调用它们(例如下面的代码)。

下面的示例脚本试图从MySQL数据库中提取足球结果,提取到CSV,然后从CSV导入并放入HTML表格并作为电子邮件发送。我遇到的问题是我需要将每个功能的输出(例如英超联赛,联赛一,联赛二)编译成报告表 - 我使用'报告'来实现:

report = ""
report += htmlpremleague
report += "<br><br>"
report += htmlleagueone
report += "<br><br>"
return report

这是加入表格所以我可以将所有结果作为HTML表格发送到一个电子邮件中。我遇到的问题是“报告”无法找到HTML,例如'htmlpremleague'由于它在一个函数中。但我不能简单地用"report += premier_league()"替换它,因为该函数中还有其他内容,而不仅仅是html。理想情况下,我希望功能正常运行,因为(a)学习它们很有趣! (b)如果能够独立经营每个联赛,那将是很酷的,例如:仅在英超联赛上制作报告。下面的示例脚本运行正常,但这是由于报告html部分是全局的并且位于函数之外。理想情况下我喜欢它们,所以我可以实现上述目标。

我是新来的,我已经尝试遵守指南,但如果我做错了什么,请告诉我,否则我可以提供更多信息。

重申一下,所需的输出将是所有要处于可调用函数的输出,例如或者,我只是将“报告”/每个表作为全局变量放置吗?

def league_one():

    query = "SELECT footballteam as ftt, goals, points FROM 
    footballdbl_league_one plfdb ORDER BY point desc"
    leagueonecursor.execute(query)
    leagueonerows = leagueonecursor.fetchall()


    with open('league_one.csv', 'wb') as file2:
        wr = csv.writer(file2, quoting=csv.QUOTE_ALL)
        wr.writerow(["Team", "Goals", "Points"])
        wr.writerows(leagueonerows)
        print ("csv2 created")

        textleagueone = """
        """
        htmlleagueone = """
        <html><body><p><u><h3><b>Highest Run Time</b></h3></u></p>
        {table2}
        <br><br>
        </body></html>
        """

        with open('league_one.csv') as input_file2:
            reader = csv.reader(input_file2)
            leagueonereader = list(reader)

            textleagueone = 
            textleagueone.format(table2=tabulate(leagueonereader, 
            headers="firstrow", tablefmt="grid"))
            htmlleagueone = 
            htmlleagueone.format(table2=tabulate(leagueonereader, 
            headers="firstrow", tablefmt="html"))

/主要示例足球脚本:

con = pymysql.connect(user='',password='',host='',database='')
cursor = con.cursor()

# probably not necessary
premleaguecursor = con.cursor()
leagueonecursor = con.cursor()

def premier_league():
    query = "SELECT footballteam as ftt, goals, points FROM footballdbl_prem_league plfdb ORDER BY point desc"
    premleaguecursor.execute(query)
    premleaguerows = premleaguecursor.fetchall()

    with open('prem_league.csv', 'wb') as file1:
        wr = csv.writer(file1, quoting=csv.QUOTE_ALL)
        wr.writerow(["Team", "Goals", "Points"])
        wr.writerows(premleaguerows)
        print ("premier league csv created")

textpremleague = """
"""

htmlpremleague = """
<html><body><p><font size="+1"><u><h3><b>Premier League</b></h3></u></font></p>
{table1}
</body></html>
    """

with open('prem_league.csv') as input_file1:
    reader = csv.reader(input_file1)
    premleaguereader = list(reader)

textpremleague = textpremleague.format(table1=tabulate(premleaguereader, headers="firstrow", tablefmt="grid"))
htmlpremleague = htmlpremleague.format(table1=tabulate(premleaguereader, headers="firstrow", tablefmt="html"))

def league_one():

    query = "SELECT footballteam as ftt, goals, points FROM footballdbl_league_one plfdb ORDER BY point desc"
    leagueonecursor.execute(query)
    leagueonerows = leagueonecursor.fetchall()


    with open('league_one.csv', 'wb') as file2:
        wr = csv.writer(file2, quoting=csv.QUOTE_ALL)
        wr.writerow(["Team", "Goals", "Points"])
        wr.writerows(leagueonerows)
        print ("csv2 created")

textleagueone = """
"""

htmlleagueone = """
<html><body><p><u><h3><b>Highest Run Time</b></h3></u></p>
{table2}
<br><br>
</body></html>
"""

with open('league_one.csv') as input_file2:
    reader = csv.reader(input_file2)
    leagueonereader = list(reader)

textleagueone = textleagueone.format(table2=tabulate(leagueonereader, headers="firstrow", tablefmt="grid"))
htmlleagueone = htmlleagueone.format(table2=tabulate(leagueonereader, headers="firstrow", tablefmt="html"))

# def league_two():

# def league_three():

def report():
    report = ""
    report += htmlpremleague
    report += "<br><br>"
    report += htmlleagueone
    report += "<br><br>"
    return report


def send_email():

    report()
    me = ''
    password = ''
    server = ''
    you = ''

    message = MIMEMultipart(
        "alternative", None, [MIMEText(report, 'html')])

    message['Subject'] = "FOOTBALL REPORT"
    message['From'] = me
    message['To'] = you
    server = smtplib.SMTP(server)
    server.ehlo()
    server.starttls()
    server.login(me, password)
    server.sendmail(me, you, message.as_string())
    server.quit()

def main():
    premier_league()
    league_one()
    report()
    send_email()

1 个答案:

答案 0 :(得分:0)

只需在def中提供您需要的数据 - 我选择将其作为列表进行操作,您也可以像def report2(myOne, myTwo): ...一样谨慎传递,并将其称为report2(one,two) - 不需要使用全局变量。

def leageOne():
    # do stuff
    stuff = "MyLeageOneResult"
    return stuff

def leageTwo():
    # do otherstuff
    otherstuff = "MyOtherResult"
    return otherstuff

def report(myInputList):
    return '<br/>'.join(myInputList)


one = leageOne()
two = leageTwo()

email = report([one , two])

print email

输出:

MyLeageOneResult<br/>MyOtherResult