Your option is great for solving the output of the script to the file.
But if in the future it becomes necessary to divide the output by type: error or information and to increase the readability of the logs, you can use logging for the place print .
This will allow you to output directly to the file and the screen, it is possible to easily track when the output was and where.
import logging import logging.handlers logger = None def set_logging(): global logger logger = logging.getLogger("main") logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(filename)s[%(lineno)-2d] %(levelname)-1s [%(asctime)s] %(message)s') file_logger = logging.handlers.RotatingFileHandler("adduser.log", maxBytes=10000000, backupCount=5) file_logger.setLevel(logging.DEBUG) file_logger.setFormatter(formatter) console_logger = logging.StreamHandler() console_logger.setLevel(logging.DEBUG) console_logger.setFormatter(formatter) logger.addHandler(file_logger) logger.addHandler(console_logger) set_logging() logger.debug("DEBUG INFO") logger.error("ERROR INFO") logger.warning('WARNING INFO') logger.info('INFO?')
Conclusion:
test.py[21] DEBUG [2017-01-27 14:13:25,600] DEBUG INFO test.py[22] ERROR [2017-01-27 14:13:25,601] ERROR INFO test.py[23] WARNING [2017-01-27 14:13:25,601] WARNING INFO test.py[24] INFO [2017-01-27 14:13:25,602] INFO?
print()is quite suitable — simple and can work even when more complex logging code that writes to a file is less convenient, for example, fordocker logs. - jfsprint, but with a bunch of advantages. And not to say that the entrylogging.info('something')much more complicated thanprint('something'). - faoxis