Home > front end >  How can i write cmd error in a file to check my python programm?
How can i write cmd error in a file to check my python programm?

Time:07-13

I want to write a report of my python program while using cmd. I have some few line of print command in my python program.

When I write :

C:/monchemin>program.py>report.txt

Ok, cool, I find all my print in a txt file, but I search to print the error who is write in my cmd. For example if the cmd say me :

variable x doesn't exist

I need to keep this error in the report.

Thanks for your help

CodePudding user response:

You can redirect stderr to stdout with:

C:/monchemin>program.py>report.txt 2>&1

CodePudding user response:

Python's logging module is the best way to handle getting output to a file. This will prove MUCH more flexible and useful than RAW prints when working on bigger projects. Handling redirects from stdout and stderr can be added like in that answer.

import logging, sys
class LoggerWriter:
    def __init__(self, level):
        self.level = level

    def write(self, message):
        if message != '\n':
            self.level(message)

    def flush(self):
        pass

log = logging.basicConfig(level = logging.WARN, filename="log.txt")


logging.error("This will be logged") # level error > warn
logging.info("This will not be logged") # level info < warn

print("This will not be logged")
#raise TypeError("This will not be logged")

sys.stdout = LoggerWriter(logging.debug)
sys.stderr = LoggerWriter(logging.warning)

print("This will BE logged")
raise TypeError("This will BE logged")

As you can see, there is much greater control over what will and will not be printed to console and what will be saved into a file.

CodePudding user response:

The script execution from command line, write all the messages into file "report.txt", you can use below mentione syntax

C:/monchemin>program.py 1> report.txt 2>&1
  • The standard output is directed to the "report.txt" file identified by output number 1.
  • The standard error output identified by the number 2 is redirected to the output file identified by number 1.

You can also turn off either Standard Output or Standard Error by redirecting the output to a NUL instead of a file.

For example
C:/monchemin>program.py 1> report.txt 2>nul

Only redirect the Standard Output (report.txt file), but the error won’t display inside the console also not create an error log file.

Other option is to adds logging calls to "program.py" code to indicate that certain events have occurred. Events also have an importance also called the level or severity.

  • DEBUG : Detailed information, typically of interest only when diagnosing problems.
  • INFO : Confirmation that things are working as expected.
  • WARNING :An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
  • ERROR : Due to a more serious problem, the software has not been able to perform some function.
  • CRITICAL : A serious error, indicating that the program itself may be unable to continue running.

script : program.py (add import logging module)

import logging

# The basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger.
#  If you run the above script several times, the messages from successive runs are appended to the file ==> default filemode='a'
logging.basicConfig(filename='report.txt', encoding='utf-8', level=logging.DEBUG)

# If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the filemode argument to filemode='w'
# logging.basicConfig(filename='report.txt', filemode='w', level=logging.DEBUG)

#Logs a message with level DEBUG on the root logger (to report.txt file).
logging.debug('This message should go to the log file')
#Logs a message with level INFO on the root logger (to report.txt file).
logging.info('So should this')
# Logs a message with level WARNING  on the root logger (to report.txt file).
logging.warning('And this, too')
# Logs a message with level ERROR  on the root logger (to report.txt file) .
logging.error('variable x doesn't exist')

Link: please check https://docs.python.org/3/howto/logging.html

  • Related