Assume I run python scripts everyday, and I need to receive a mail when my python script runs out with error. In pycharm I could save the console output to file, can anyone help me how to save the console output to a file by python script.
Asked
Active
Viewed 2,882 times
-3
-
1Run it from a shell script, which can redirect output to a file. – Barmar Dec 29 '21 at 04:53
-
1https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files or https://askubuntu.com/questions/420981/how-do-i-save-terminal-output-to-a-file (if on Linux) or https://stackoverflow.com/questions/1215260/how-to-redirect-the-output-of-a-powershell-to-a-file-during-its-execution if on Windows. This is an *extremely common task* and well-documented for virtually all environments. – msanford Dec 29 '21 at 04:53
-
Then check if the file is empty, and mail it if not. – Barmar Dec 29 '21 at 04:53
1 Answers
3
Using Logging
It's time to become familiar with logging in python. See Logging HOWTO. More specifically, see logging to a file.
From the docs:
import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
If you use this module for logging rather than print
, it will send all output to a file called example.log
(in the same folder as the program was started)
Redirecting stdout
If you don't want to spend the time to learn to use the logging module, the print function will do as well, but we have to slightly modify standard output for your program.
You can do the following at the start of your python script (taken from this answer):
from contextlib import redirect_stdout
with open('example.log', 'w') as f:
with redirect_stdout(f):
print('it now prints to `example.log`')
# the rest of your code or main function goes here

smac89
- 39,374
- 15
- 132
- 179
-
thanks. how can I print both in a file and console per each run of the script using the second approach? – Reiso Oct 27 '22 at 06:51