Python 代码运行良好,直到放入函数

Python code runs fine, until put into a function

所以我开发了 python 代码,以短信的形式发送报价。它在一个简单的脚本中 运行 时正常运行。但是,一旦我将代码放入一个函数中并调用该函数,它就无法工作。它发送一条空白短信,而不是报价。

这是有效的代码:

import smtplib
import urllib2

''' open webpage and grab randomly generated quote '''
response = urllib2.urlopen("http://inspirationalshit.com/quotes")
page = response.read()
split = page.split('<blockquote>')[1]
split = split.split('class="text-uppercase";>')[1]
quote = split.split('</p>')[0].strip()

'''email credentials (throwaway account) '''
username = "**********@gmail.com"
password = "*********"
phone = "********@vtext.com"
message = quote

''' format the email '''
msg = """From: %s
To: %s
Subject:
%s""" % (username, phone, message)

''' send the email '''
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(username, password)
server.sendmail(username, phone, msg)
server.quit()

这是非功能代码

import urllib2
import smtplib
import schedule
import time


def job():
    print "RAN"
    ''' open webpage and grab randomly generated quote '''
    response = urllib2.urlopen("http://inspirationalshit.com/quotes")
    page = response.read()
    split = page.split('<blockquote>')[1]
    split = split.split('class="text-uppercase";>')[1]
    quote = split.split('</p>')[0].strip()

    '''email credentials (throwaway account) '''
    username = "*********@gmail.com"
    password = "********"
    phone = "********@vtext.com"
    message = quote

    ''' format the email '''
    msg = """From: %s
    To: %s
    Subject:
    %s""" % (username, phone, message)
    print msg
    ''' send the email '''
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(username, password)
    server.sendmail(username, phone, msg)
    server.quit()


job()
    ''' format the email '''
    msg = """From: %s
    To: %s
    Subject:
    %s""" % (username, phone, message)
    print msg

可能sendmail对该字符串每行开头的空格敏感。尝试 de-indenting 个。

    ''' format the email '''
    msg = """From: %s
To: %s
Subject:
%s""" % (username, phone, message)
    print msg