defisequal(output,right_output): if output == right_output: returnTrue else: printu'不相等'
那么恭喜你,你步入正规了,然而,这一切已经有人为你做好了。欢迎unittest模块出场。
unittest supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests.
#-*-coding:utf-8-*- from flask import Flask app = Flask(__name__)
@app.route('/') def index(): f = open('mail_note.log','rb') #以读文件的方式打开mail_note.log文件 content = f.readlines()#按行读取日志 s = '' for each in content: s += each s += '</p>'#输出日志 f.close() return s
if __name__ == '__main__': app.run(host='0.0.0.0') #开发外网访问
#-*-coding:utf-8-*- from flask import Flask app = Flask(__name__)
@app.route('/') def index(): f = open('mail_note.log','rb') #以读文件的方式打开mail_note.log文件 content = f.readlines()#按行读取日志 s = '' for each in content: if 'gmail_helper.py' in each: #判定信息来自gmail_helper.py而不是discovery.py s += each s += '</p>'#输出日志 f.close() return s
if __name__ == '__main__': app.run(host='0.0.0.0') #开发外网访问
ubuntu@ip-172-31-15-35:~$ screen -ls There is a screen on: 7956.pts-0.ip-172-31-15-35 (01/01/2015 12:16:10 PM) (Detached) 1 Socket in /var/run/screen/S-ubuntu.
def init(): global last_email last_email = ListMessagesWithLabels(gmail_service,'me')[0]['id']
def isnew(): global last_email themail = ListMessagesWithLabels(gmail_service,'me') for each in themail: if each['id'] != last_email: tosend(each['id']) else: break last_email = themail[0]['id']
def tosend(id): b = GetMessage(gmail_service,'me',id) content = b['snippet'] sender = b['payload']['headers'][3]['value'] subject = b['payload']['headers'][12]['value'] body = sender + '\n' + content send_mail(subject,body) print subject print body print '============================'
设定一个主函数,并把上面的代码放在主函数里面,并循环执行:
1 2 3 4 5
if __name__=='__main__': init() while 1: time.sleep(3600) #每一小时检查一次邮箱 isnew()
from apiclient.discovery import build from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import run
# Path to the client_secret.json file downloaded from the Developer Console CLIENT_SECRET_FILE = 'client_secret.json'
# Check https://developers.google.com/gmail/api/auth/scopes for all available scopes OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'
# Location of the credentials storage file STORAGE = Storage('gmail.storage')
# Start the OAuth flow to retrieve credentials flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE) http = httplib2.Http()
# Try to retrieve credentials from storage or run the flow to generate them credentials = STORAGE.get() if credentials is None or credentials.invalid: credentials = run(flow, STORAGE, http=http)
# Authorize the httplib2.Http object with our credentials http = credentials.authorize(http)
# Build the Gmail service from discovery gmail_service = build('gmail', 'v1', http=http)
# Retrieve a page of threads threads = gmail_service.users().threads().list(userId='me').execute()
# Print ID for each thread if threads['threads']: for thread in threads['threads']: print 'Thread ID: %s' % (thread['id'])
from apiclient.discovery import build from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import run from apiclient import errors import base64 import email
# Path to the client_secret.json file downloaded from the Developer Console CLIENT_SECRET_FILE = 'client_secret.json'
# Check https://developers.google.com/gmail/api/auth/scopes for all available scopes OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'
# Location of the credentials storage file STORAGE = Storage('gmail.storage')
# Start the OAuth flow to retrieve credentials flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE) http = httplib2.Http()
# Try to retrieve credentials from storage or run the flow to generate them credentials = STORAGE.get() if credentials is None or credentials.invalid: credentials = run(flow, STORAGE, http=http)
# Authorize the httplib2.Http object with our credentials http = credentials.authorize(http)
# Build the Gmail service from discovery gmail_service = build('gmail', 'v1', http=http)
# Retrieve a page of threads # threads = gmail_service.users().threads().list(userId='me').execute()
# # Print ID for each thread # if threads['threads']: # for thread in threads['threads']: # print 'Thread ID: %s' % (thread['id'])
def ListMessagesWithLabels(service, user_id, label_ids=[]): """List all Messages of the user's mailbox with label_ids applied.
Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. label_ids: Only return Messages with these labelIds applied.
Returns: List of Messages that have all required Labels applied. Note that the returned list contains Message IDs, you must use get with the appropriate id to get the details of a Message. """ try: response = service.users().messages().list(userId=user_id, labelIds=label_ids).execute() messages = [] if 'messages' in response: messages.extend(response['messages'])
while 'nextPageToken' in response: page_token = response['nextPageToken'] response = service.users().messages().list(userId=user_id, labelIds=label_ids, pageToken=page_token).execute() messages.extend(response['messages'])
def GetMessage(service, user_id, msg_id): """Get a Message with given ID.
Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. msg_id: The ID of the Message required.
Returns: A Message. """ try: message = service.users().messages().get(userId=user_id, id=msg_id).execute()
a = ListMessagesWithLabels(gmail_service,'me')[0]['id'] b = GetMessage(gmail_service,'me',a) print b['snippet'] print b['payload']['headers'][3]['value']