My script currently works to send me an error alert if my .py script fails. However, sometimes the script is not necessarily failing. its just that there are no files for it to process. My final objective is to alter my email alerting script in such a way that if Combine.csv is not present in directory(src),then DONT send me error an email. How do i achieve this?
import pandas as pd
import smtplib
from email.message import EmailMessage
import glob
import os
import shutil
df = pd.read_fwf(r'Combine.csv', header=None)
end_str = '#--- END --'
cols_to_check = ["0"]
def email_alert(subject,body,to):
msg = EmailMessage()
msg.set_content(body)
msg['subject'] = subject
msg['to'] = to
user = "[email protected]"
msg['from'] = user
server = smtplib.SMTP("smtpray.corp.group.com", 25)
server.starttls()
#server.login(user,password)
server.send_message(msg)
server.quit()
src = r'C:/R'
dest = r'C:/R/Failed Scripts'
if __name__ == '__main__':
for col in cols_to_check:
if not df[0].str.contains(end_str).any():
body = "The Combine.py script in IV had errors on the last execution" col "."
print(body)
email_alert("Combine failure alert",body,"[email protected]")
if not df[0].str.contains(end_str).any():
for file_path in glob.glob(os.path.join(src,'*.Rout'), recursive=True):
new_path = os.path.join(dest, os.path.basename(file_path))
shutil.copy(file_path, new_path)
CodePudding user response:
Just check whether the file you want to read exists:
import os
file_name = "Combine.csv"
cwd = os.getcwd()
file_path = os.path.join(cwd, file_name)
if not os.path.exists(file_path):
exit()
cwd means current working directory and is the path to the directory your python file runs in. Then path.join just combines your file name with the path to your directory so that you have an absolute path. Then you can check whether than file exists using the path.exist function.
CodePudding user response:
To eliminate inspection of what the 'end' terminator, we can evaluate the size of the dataframe and exit the loop (or script) if appropriate.
if len(df) == 1:
break # exit()
The break
keyword may be ideal if exiting a loop. However, if the data is pulled from combine.csv
, then exit()
to terminate the script may be more appropriate.