4

I have a python function which prints some lines on terminal.

Here is how I execute the function:

python3 test.py

Here is some code from the file:

column1 = "|=========="
        column2 = "|==============================================================="
        column3 = "|==================================="
        column4 = "|======================="

        print("\n"+column1+column2+column3+column4+"|")
        print("|SCRIPT ID    |SCRIPT NAME                                                       |Start Time                         |RUN ID             |")
        print(column1+column2+column3+column4+"|")

It prints the following in terminal:

|==========|===============================================================|===================================|=======================|
|SCRIPT ID    |SCRIPT NAME                                                       |Start Time                         | RUN ID             |
|==========|===============================================================|===================================|=======================|
|1         |TEST_SCRIPT                                    |2020-04-17 11:46:28.054074+05:30   |201                    |
|==========|===============================================================|===================================|=======================|

Entering - SCRIPT
     Verification Started
     Verification Completed in 0 Hours 00 Min 00.000602 sec
     Methods Execution Started
     Methods Execution Completed
EXITING - SCRIPT

I want to maintain the output of the function in a log file. So, if I run python3 test.py, it should create a file called test.py-202004171148.log in a folder called as logs storing all the output in the file.

How can I do this?

9
  • provide some code from test.py Commented Apr 17, 2020 at 6:21
  • added some code from the file. Commented Apr 17, 2020 at 6:24
  • You could just do, python3 test.py > filename.log Commented Apr 17, 2020 at 6:25
  • do you want save test.py-202004171148.log with timestamp or just random numbers? Commented Apr 17, 2020 at 6:28
  • Is it possible to generate the file without writing filename.log every time? Commented Apr 17, 2020 at 6:28

4 Answers 4

3

save file with datetime:

import datetime
file = open(str(datetime.now().strftime('test.py-%Y%m%d%H%M%S.log')), "w")
file.write("yourlogs")
file.close()
Sign up to request clarification or add additional context in comments.

Comments

1

to saving file you can use:

import datetime
file = open("test.py-"+str(datetime.datetime.now().timestamp())+".log", "w")
file.write("yourlogs")
file.close()

Comments

1

Adding these few lines of code to the top of your script should redirect all output to be printed to console AND ALSO written to a file

import sys
import datetime

class Printer(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for file in self.files:
            file.write(obj)
            file.flush()
    def flush(self):
        for file in self.files:
            file.flush()

f = open(f"{__file__}-{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.log", 'w')
sys.stdout = Printer(sys.stdout, f)

#Your print statements below
print("Hello world!")

10 Comments

Can we put the function name and put in the folder - logs
Also, can I print on screen and also save to file
Yes, you can create a folder logs, and save all your output to it. I will edit my answer to reflect the same.
Would be nice to get the filename dynamically. For example, if it is test.py-20200417.log or abc.py-20200427.log
You can access the filename in the variable __file__
|
0

You can use the logging module for that. You will have to replace print() with logging.info(), logging.warning(), or logging.error() depending on your desired log level.

import logging
from datetime import datetime
fn = datetime.now().strftime('logs/test.py-%Y%m%d%H%M%S.log')
logging.basicConfig(filename=fn, level=logging.INFO)
logging.info('Entering - SCRIPT')
logging.info('etc...')

The default format will prefix every message with the log level and logger name. If you don't want that, you can override it with format.

logging.basicConfig(filename=fn, level=logging.INFO, format='%(message)s')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.