0

I can print Python statements to output (in one script) but I'm getting confused with imported modules, functions, and main(). I'm doing like this:

import sys
old_stdout = sys.stdout
log_file = open("message.log","w")
sys.stdout = log_file
print("something")
sys.stdout = old_stdout
log_file.close()

In the code base I'm working on, it's like

import classes from other .py scripts

def some_big_function()
    # the code from above to print to output

def main():
    # a few print statements
    some_big_function(args)

main()

How do I get all print statements to go to one file? I put print statements in some_big_function() and it seems to work.

But what if I have print statements in main()? They won't print to output like in some_big_function().

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Chuck
  • 1,061
  • 1
  • 20
  • 45
  • 4
    You should use the logging module (https://docs.python.org/3/library/logging.html). There's a learning curve, but it's much much better than logging with print(). If you can't use logging for some reason, use `print("...", file=somefileobject)`. – jpkotta Jul 22 '21 at 19:14
  • Use logging module with different stream and file handler if you'd like to. With this way you can also set different logging levels to different outputs. E.g. you can set critical messages to written both stdout and file, debug messages to only stdout and info messages to only files. Much more efficient. – emremrah Jul 22 '21 at 19:19
  • Looking at your code example, I notice you are not passing anything to `some_big_function()` – Derek Jul 23 '21 at 01:46

0 Answers0