Home > Mobile >  Want a method to save the python output and simultaneously view the output
Want a method to save the python output and simultaneously view the output

Time:08-21

Is there any function or module to save the some part of python output to a file and also be view the output in terminal. By the way I use vs code and using linux as my os.I am ready to change my code but don't like to type something in my terminal

CodePudding user response:

I don't think you can do it with only Python. However, you can save your output with a program called tee, depending on how you run your code.

  • In case you're running it from a command line, like:
    $ python ./my-code.py
    then you just need to pipe the output into tee:
    $ python ./my-code.py | tee /path/to/saved/output
  • In case you run it directly from vscode, then you must have a config file called .vscode or something similar. That will contain a line specifying the running command, which is likely something like python my-file.py. You just need to append | tee /path/to/saved/output to that command.

CodePudding user response:

You could use the logging module and define 2 log handlers, one for stdout and one to write into a file:

import logging
import sys
logFile = '/tmp/myApp.log'

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)d - %(levelname)s: %(message)s',
    datefmt='%Y-%m-%dT%H:%M:%S',
    handlers=[logging.FileHandler(logFile),
              logging.StreamHandler(sys.stdout)]
)

Usage:

log = logging.getLogger()
log.debug("My log message")
  • Related