Answer the question
In order to leave comments, you need to log in
Python logging, how to quickly output errors to a file?
Is it possible to somehow quickly output to a file everything that python outputs to the console? Messages from the print command and errors?
os windows
python 3.4
the program is built by pyinstaller and runs on a third party computer.
Answer the question
In order to leave comments, you need to log in
I ran something like this in one situation:
old_print = print
def print(*args, **kwargs):
old_print("~", *args, "~", **kwargs)
print("qwerty")
from traceback import format_exc
try:
# do something wrong
x = 1 / 0
except:
for s in format_exc().splitlines():
print("*", s, "*")
turn on logging before it's too late. Create a logger once and change all print to logger.info - it takes about 5 minutes. In return, you will get the ability to quickly switch logging to a file / console, split messages by levels (it is very convenient to separate debugging messages from informational and diagnostic ones), full-fledged exception logging, and a bunch of other goodies.
The very first thing to do in any more or less useful script or large program is to set up logging.
In its simplest form, it can be arranged like this:
import sys
import logging
if __name__ == '__main__':
log = logging.getLogger()
log.level = logging.DEBUG
log.addHandler(logging.StreamHandler(sys.stderr))
else:
log = logging.getLogger(__name__)
## Используем так:
log.info('any text')
log.debug('Something about %r in %s', log, __name__)
## Здесь размещаем весь остальной код
if __name__ == '__main__':
pass # А здесь, если надо, размещаем то, что будет выполняться, когда модуль запускают как скрипт
log = logging.getLogger(__name__)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question