Currently, I can print information to stdout and also to stderr, but I would like to print information about progress and print it to stdout, stderr and somewhere else. Is this possible?
3 Answers
You can use the logging module to log information simultaneously to different places:
import logging logger = logging.getLogger('your_logger') logger.setLevel(logging.INFO) file_handler = logging.FileHandler('errors.log') file_handler.setLevel(logging.ERROR) logger.addHandler(file_handler) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) logger.addHandler(stream_handler) logger.warning('I am a warning') logger.error('I will be printed, but written to the log file as well') logger.info('I am an info message') 5 Comments
stderr or stdout? (I need to read up on that module)Output to the console comes only via stdout and stderr as far as I know.
Do you want to print to a file, then you can do this
with open('outfile.txt', 'w') as f: f.write('this is a test') or alternatively if you prefer using print:
print >> f, 'this is a test' In the above example a file named outfile.txt is opened for write access. This means any data already present will be wiped out by new data written to it. If you wanted to append you'd open the file in a mode. See the documentation for open() for more information.
Files that are opened need to be closed, using the with construct takes care of that for you (and also closes the file in case you encounter an exception).
3 Comments
/dev/console on a unix-like machine will probably work, although it's not necessarily a good idea.Make a class with method named write(), then you can use
print 'text' >> Printer() to print 'text' to the Printer() object (python 2.x) or
print('text', file=Printer()) in python 3.x
2 Comments
StringIO (which already has a write method).
stdout,stderr, and somewhere else?