首页 > 解决方案 > 如何继续在后台运行 python 脚本

问题描述

所以我制作了一个 python 脚本,如果我收到我指定的人的电子邮件,它会向自己发送一个文本。例如,在我输入的脚本中,如果我收到一封带有“bobby”的电子邮件,它将搜索未读电子邮件的主题和正文。如果我收到一封主题或正文中包含 bobby 的电子邮件,它会发短信告诉我我收到了 bobby 的电子邮件。

nohup python emtext_alerts.py &用来运行脚本

截至目前,如果收到一封带有“bobby”的电子邮件,它会向我发送一条短信。但如果我得到第二个,它就不会再给我发短信了。我应该如何继续搜索与 bobby 相关的电子邮件?

这是我的代码:

from twilio.rest import Client
from imapclient import IMAPClient
import os

def main():
    checkEmail()

def checkEmail():
    server = IMAPClient('imap.gmail.com', use_uid=True)                                     #connect to IMAP server
    GMAIL_PASS = os.environ['GMAIL_PASS']                                                   #insert gmail password, may need to make an app account
    server.login('cscarlossamaniego@gmail.com', GMAIL_PASS)                                 #log in

    select_info = server.select_folder('INBOX')                                             #Select folder you want to search in
    topic_to_search = 'testing'                                                             #INPUT WHAT YOU WANT TO SEARCH FOR!
    unseen_messages_subject = server.search(['(UNSEEN)', 'SUBJECT', topic_to_search])       #Searching unread emails with topic to search in subject or body
    unseen_messages_body = server.search(['(UNSEEN)', 'TEXT', topic_to_search])

    if unseen_messages_subject:                                                             #send text if topic to search is in body/subject of unread email
        print("unread message about: '{0}'".format(topic_to_search))
        sendText(topic_to_search)
    elif unseen_messages_body:
        print("unread message about: '{0}'".format(topic_to_search))
        sendText(topic_to_search)

def sendText(topic_to_search):                                                      
    account_sid = os.environ['TWILIO_ACCOUNT_SID']                                          #created Twilio account with Accound SID and token
    auth_token = os.environ['TWILIO_AUTH_TOKEN']

    client = Client(account_sid, auth_token)                                                #create connection

    myTwilioNumber = os.environ['MY_TWILIO_NUMBER']                                         #input twilio number
    myCellPhone = os.environ['MY_CELL_PHONE_NUMBER']                                        #input ur phone number

    #sends message
    message = client.messages.create(body="Email about '{0}'".format(topic_to_search), from_=myTwilioNumber, to=myCellPhone)  
    print(message.sid)

if __name__ == '__main__':
    main() 

请告诉我!

标签: pythonbackground-process

解决方案


如果您使用的是 Linux nohup:

nohup /path/to/test.py &

即使终端会话结束,这也将使 python(或任何脚本)在后台运行。

Windows 你可以使用 pythonw.exe 来运行一些东西。

pythonw.exe test.py

所有这些都假设您的脚本将循环。听起来您的脚本正在运行一次;即使您在后台运行任务,它仍然会终止。您需要添加逻辑

我会在你的脚本中建立一个循环,一个while循环

condition = 0
while condition = 0:
    Run Your Code

将 Run Your Code 替换为您要执行的代码块。

这将使您的任务在后台运行,同时确保 Python 仍在检查您的电子邮件


推荐阅读