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