-1

Is there a way to save the program input and output to a text file? Let's have a really simple application and say I want to log the shell to a "log.txt" file.

What's your name?
Peter

How old are you?
35

Where are your from?
Germany

Hi Peter, you're 35 years old and you're from Germany!

I believe that the logging module could be the way but I don't know how to use it.

tears
  • 11
  • u can use logging to store input and output – Tanveer Ahmad Jan 11 '23 at 13:56
  • You can use the logging module as answered previously, or check out these two posts to see various other ways to capture user input into a file: https://stackoverflow.com/q/61291251/9587457, https://stackoverflow.com/q/3011680/9587457 – DriveItLikeYouStoleIt Jan 11 '23 at 14:38

1 Answers1

0

In the official documentation there is a Basic Logging Tutorial.

A very simple example would be:

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ö')

That's the explanation: First you import logging, and after that you configure it with basicConfig indicating the file that you want to save the log messages to.

Then, every time you want to add something to the log, you have to use the logging functions: debug(), info(), warning(), error() and critical(), that are named after the level or severity of the events they are used to track.

tomasborrella
  • 480
  • 2
  • 8