python - Windows Task Scheduler 运行可执行文件而不读取文件

我试图让 Task Scheduler 在 windows 启动时运行一个可执行文件。可执行文件是一个简单的 python 脚本,它从 .txt 中读取 IP 列表,对它们执行 ping 操作,并在设定的时间间隔后重复,就像基本的心跳一样。

该可执行文件是使用 pyinstaller 成功创建的,并且在手动使用时可以完美运行。

但是,当我尝试让 task scheduler 在同一目录中运行相同的可执行文件时,它不会读取 .txt 文件并立即关闭。

以下是代码,

import os
import time
import smtplib
from email.message import EmailMessage #allows for the email system to work
from datetime import datetime #allows the text files to have the date & time
from win10toast import ToastNotifier #allows for desktop notificaitons to appear on windows devices
import schedule #automatically schedules when the script executes

# Scans the IPs in the txt file
def notif():
    with open (r'sydvlan.txt') as file:   
        dump = file.read() #reads the lines of the sydvlan.txt file
        dump = dump.splitlines()
            #creates a new log file and makes the title the current date and time
        cdString = datetime.now().strftime("%d_%m_%Y %H_%M") 
        
        report = open(r'HeartbeatResults_{0}.txt'.format(cdString), 'w') #creates a log with the date&time
        
        for line in dump:
            lineList = line.split(":") 
            lineText =  lineList[0]    #makes sure that only the IP is being read from sydvlan.txt
            IP = lineList[1].strip()
            print("Currently Pinging {} on {}".format(lineText,IP))
            print("------------------"*3)

            # Get Date and Time at time of ping.
            currentDate = datetime.now()
            cdString = currentDate.strftime("%d_%m_%Y %H:%M:%S") 
            # pings the IPs from the txt
            response = os.popen(f"ping {IP} -n 4").read() #pings the device
            print("------------------"*3)

            # If the os.popen() returns 0, it means the operation completed without any errors, so if it returns 0 it is successful.

            if "Received >= 1" and "Approximate" in response:
                report.write("UP {0} Successful {1}".format(lineText, cdString) + "\n")
            else:
                report.write("DOWN {0} UnSuccessful {1}".format(lineText, cdString) + "\n")

           
            if "Received = 0" or "unreachable" in response: #Sends an email to IT staff if the ping fails
                #composes the email message
                #email_alert("Issue with {0}".format(lineText, cdString), "The Hearbeat Notification System Works :)")

                toaster = ToastNotifier()
               
                toaster.show_toast("Issue with {0}: {1} on {2}".format(lineText, IP, cdString), "Please Fix Now", duration=10, icon_path='Warning.ico')

            time.sleep(1)
                   

    report.write("Hearbeat Protocol Complete" + "\n")
    file.close()


#email notification setup
#def email_alert(subject, body):
#    mailListFile = open(r'XXXXX.txt')
#    emailList = (mailListFile.read()).splitlines()

#    msg = EmailMessage()
#    msg.set_content(body)
#    msg['subject'] = subject
#    msg['to'] = ', '.join(emailList)
    
#    user = "XXXXX"
#    msg['from'] = user 
#    password = "XXXXXX"
#    server = smtplib.SMTP("smtp.gmail.com", 587) 
#    server.starttls()
#    server.login(user, password)
#    server.send_message(msg)
    
#    server.quit()
        
#allows for the entire script to run every 300 seconds (or whatever is specified)
if __name__ == '__main__': 
    notif()
    while True:
        schedule.run_pending()
        time.sleep(1)
        schedule.every(5).minutes.do(notif)

创建可执行文件时我使用的唯一参数是 --onefile

感谢您的时间。

回答1

您的文件名 r'sydvlan.txt' 是一个相对路径,因此它的位置取决于调用程序时的当前工作目录。

要么尝试使用绝对路径,例如r'C:\path\to\file\sydvlan.txt'(也为 r'HeartbeatResults_{0}.txt' 执行此操作)或将 Windows task scheduler 中的“开始于(可选)”参数设置为 txt 文件所在的路径。

相似文章

随机推荐

最新文章