1

Could you help me that when I compile my program and if I have an error how can I redirect this error message in text file, before compilation terminate?

I wrote this code, But my problem is i want when i have an error after that my COMP_ERR.txt file create and write error inside this file. but in my code this create before

import urllib.request
import os
import tempfile
import sys
import fileinput


original_stderr = sys.stderr
f_error = open("COMP_ERR.txt", "w")
sys.stderr = f_error
try:
    url = sys.argv[1]
    path_snip_file = sys.argv[2]

    #url = 'http://pages.di.unipi.it/corradini/Didattica/AP-17/PROG-ASS/03/ClassWithTest.java'
    #path_snip_file = "C:/Users/user/AppData/Local/Programs/Python/Python36/snip1.java"

    path_remote_file_inOurComp = "C:/Users/user/AppData/Local/Programs/Python/Python36/ClassWithTest.java"
    path_remote_file_inOurCom = "C:/Users/user/AppData/Local/Programs/Python/Python36/ClassWithTest1.java"
    gt_url = urllib.request.urlretrieve(url)

    print("the URL is: ") 
    print(gt_url)
    link = input("input the path of file: ")

    """
    f = open(link, "r")
    for line in f:
        print(line, end='')
    f.close()
    """

    #--------------------]
    #copy snipper java file inside remote file
    #[--------------------


    with open(path_remote_file_inOurComp, 'w') as modify_file:
        with open (link, 'r') as r_file:
            for line in r_file:
                if " public static void main(" not in line:
                    modify_file.write(line)
                else:
                    with open(path_snip_file, 'r') as snip_file:
                        for lines in snip_file:
                            modify_file.write(lines)
                    modify_file.write('\n'+line)
    #-------------------------------------------------------------
    #refactor
    #-------------------------------------------------------------
    with open(path_remote_file_inOurCom, 'w') as ft:
        with open(path_remote_file_inOurComp, 'r') as file_n:
            for line in file_n:
                line = line.replace("System.out.println(", "System.out.println(insertLength(")
                line = line.replace(";", ");")
                ft.write(line)


except IndexError:
    print("Not enough input! ! !")
sys.stderr = original_stderr
f_error.close()
saharsa
  • 467
  • 1
  • 7
  • 24

3 Answers3

0
logf = open("download.log", "w")
for download in download_list:
    try:
        # code to process download here
    except Exception as e:     # most generic exception you can catch
        logf.write("Failed to download {0}: {1}\n".format(str(download), str(e)))
        # optional: delete local version of failed download
    finally:
        # optional clean up code
        pass

apart from this approach, you can use logging library to save each and every logs of your application.

Following is the method 2 of the problem of saving logs.

import logging
logging.basicConfig(filename='gunicon-server.log',level=logging.DEBUG,
                    format='[%(levelname)s]: [%(asctime)s] [%(message)s]', datefmt='%m/%d/%Y %I:%M:%S %p')
try:
    # code to process download here
except Exception as e:     # most generic exception you can catch
    logging.error(str(e))
finally:
    # optional clean up code
    pass
Rishabh K Sharma
  • 239
  • 4
  • 15
0

Check if it is useful to you

import sys
try:
   raise
except Exception as err:
      **exc_type, exc_obj, exc_tb = sys.exc_info()**  # this is to get error line number and description.
      file_name = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]  # to get File Name.
      error_string="ERROR : Error Msg:{},File Name : {}, Line no : {}\n".format(err,file_name,exc_tb.tb_lineno))
      file_log = open("error_log.log", "a")
      file_log.write(error_string)
      file_log.close()
Sagar T
  • 89
  • 1
  • 1
  • 11
  • could you tell me how can i define for program that what is my filename? because i want redirect to text file – saharsa Jan 11 '18 at 16:24
  • I used logging for redirect to text file and for this you have define in filename='your text file name'. like this: logging.basicConfig(filename="YOUR TEXT FILE NAME.TXT", level= logging.ERROR) and i have to point that i did chose the level of ERROR but you can choose another level – saharsa Jan 12 '18 at 13:05
0
import sys
sys.stderr = open('errorlog.txt', 'w')

# do whatever

sys.stderr.close()
sys.stderr = sys.__stderr__

see this for more details : https://ubuntuforums.org/showthread.php?t=849752

Mhadhbi issam
  • 197
  • 3
  • 6