1

I want to capture terminal message and save it to a text file while my python script is running.. I want to capture error messages as well.

-Don't want to execute this using batch file. -help me where should i put those command on my script

import base64

import sendgrid

import os

import pandas as pd

import time

from datetime import date, timedelta


from sendgrid.helpers.mail import Email, Content, Mail, Attachment

    # Python 3
    import urllib.request as urllib

except ImportError:

    # Python 2
    import urllib2 as urllib


list = pd.read_csv('emaildb.csv')

email = list['Email']

merchant = list['Merchant']

today = date.today()

yest = today - timedelta(1)

yest1 = yest.strftime('%Y%m%d')

yest2 = yest.strftime('%Y-%m-%d')

now1 = time.strftime("%B %d %Y  %H:%M:%S") 

sg = sendgrid.SendGridAPIClient(apikey='sample API')



i = 0

while i < len(list):

    file_name1 = "REPORT_"+yest1+"_"+str(merchant[i])+".pdf"

    file_name2 = "REPORT_"+yest1+"_"+str(merchant[i])+".xls"

    S1="REPORT "+str(merchant[i])+" "+str(yest1)

    B1 = "Test"

    with open(file_name1,'rb') as f:
        data1 = f.read()
    encoded1 = base64.b64encode(data1).decode()



    with open(file_name2,'rb') as f:
        data2 = f.read()
    encoded2 = base64.b64encode(data2).decode()

    mail = {
        "attachments": [
        {
          "content": encoded1, 

          "filename": file_name1,
        },
        {
          "content": encoded2,
          "filename": file_name2,
        }
      ],      
      "personalizations": [
        {

          "to": [{
              "email": email[i]
          }],
          "subject": S1
        }
      ],
      "from": {
        "email": "test.com"
      },
      "content": [
        {
          "type": "text/html",
          "value": B1
        }
      ]
    }

    response = sg.client.mail.send.post(request_body=mail)
    print("["+now1+"] "+email[i]+" "+file_name1)
    if response.status_code == 202:
        print('Success')
    else: print('Failed')
    print("\n")
    i = i + 1
11
  • 3
    $ python script_name.py > logs.txt 2> errors.txt Commented May 14, 2019 at 5:09
  • what if i want to include date and time on the text file? Commented May 14, 2019 at 5:15
  • Do you want to redirect some statement from within your python file? Or just redirect whatever gets printed out from the script to a file @Cel Commented May 14, 2019 at 5:18
  • @DeveshKumarSingh i want to print to .txt file whatever the output message in the terminal, btw im calling the python script via .bat and scheduled it to run via windows task scheduler. Commented May 14, 2019 at 5:32
  • 1
    Then use a logger module where you direct whatever you want from within the file! Commented May 14, 2019 at 5:38

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.