在python3中的txt文件中保存错误编译消息

时间:2018-01-11 12:26:27

标签: python python-3.x

在编译我的程序时是否可以帮助我?如果我有错误,如何在编译终止之前将此错误消息重定向到文本文件中?

我写了这段代码,但我的问题是我想在我的COMP_ERR.txt文件在此文件中创建和写入错误之后发生错误。 但在我的代码中,这是在

之前创建的
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()

3 个答案:

答案 0 :(得分: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

除了这种方法,您还可以使用日志库来保存应用程序的每个日志。

以下是保存日志问题的方法2。

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

答案 1 :(得分:0)

检查它是否对您有用

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()

答案 2 :(得分:0)

import sys
sys.stderr = open('errorlog.txt', 'w')

# do whatever

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

有关详情,请参见:https://ubuntuforums.org/showthread.php?t=849752