完成你所需要的一種強有力的方法是使用Python Web框架Flask(http://flask.pocoo.org/)。有Youtube視頻可以很好地解釋Flask的基礎知識(https://www.youtube.com/watch?v=ZVGwqnjOKjk)。
下面是我的動作探測器的一個例子,當我的貓在門口等待時,它給我發短信。所有需要做的事情都是爲了在這個地址發送HTTP請求(在我的情況下)http://192.168.1.112:5000/cat_detected
from flask import Flask
import smtplib
import time
def email(from_address, to_address, email_subject, email_message):
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
# For character type new-lines, change the header to read: "Content-Type: text/plain". Use the double \r\n.
# For HTML style tags for your new-lines, change the header to read: "Content-Type: text/html". Use line-breaks <br>.
headers = "\r\n".join(["from: " + from_address, "subject: " + email_subject,
"to: " + to_address,
"mime-version: 1.0",
"content-type: text/plain"])
message = headers + '\r\n' + email_message
server.sendmail(from_address, to_address, message)
server.quit()
return time.strftime('%Y-%m-%d, %H:%M:%S')
app = Flask(__name__)
@app.route('/cat_detected', methods=['GET'])
def cat_detected():
fromaddr = 'CAT ALERT'
admin_addrs_list = [['[email protected]', 'Mark']] # Use your carrier's format for sending text messages via email.
for y in admin_addrs_list:
email(fromaddr, y[0], 'CAT ALERT', 'Carbon life-form standing by the door.')
print('Email on its way!', time.strftime('%Y-%m-%d, %H:%M:%S'))
return 'Email Sent!'
if __name__ == '__main__':
username = '[email protected]'
password = 'yourGmailPassword'
app.run(host='0.0.0.0', threaded=True)
首先,你需要一個web服務器。您是否已經安裝並在該計算機上運行了Web服務器? –
如果你使用Windows這個鏈接可能工作http://stackoverflow.com/questions/3179657/python-webbrowser-question –
我想你誤解了我。我希望Python腳本充當某種Web服務器,除非我不需要提供任何文件。當客戶端訪問服務器上的URL時,我需要能夠執行一個函數。 – Lazze