Python Forum
How to "tee" (=split) output to screen and into file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to "tee" (=split) output to screen and into file?
#1
Assume I want to write something from inside a *.py script to screen AND into file D:\tools\python\myoutput.log

How can I achive this WITHOUT executing the same command twice?

Is there something linke a "tee" command similar to

print ("hello") | >D:\tools\üython\myoutput.log
Reply
#2
I don't know that you can do that with a single command, but I would do this:

with open("file_name", mode='w', encoding='UTF8') as output:
    something = "This is what you want to write"
    print(something)
    print(something, file=output)
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
You can simulate it by replacing temporarily sys.stdout with a custom file object that contains a pointer to the new file
import contextlib
import sys

class _Tee:
    def __init__(self, *files):
        self.files = files

    def write(self, s):
        for f in self.files:
            f.write(s)
        return len(s)  # not perfect

    def flush(self):
        for f in self.files:
            f.flush()


@contextlib.contextmanager
def tee(filename):
    stdout = sys.stdout
    try:
        with open(filename, 'w') as f:
            sys.stdout = _Tee(sys.stdout, f)
            yield sys.stdout
    finally:
        sys.stdout = stdout

def main():
    print('hello')
    print('bye')

if __name__ == '__main__':

    with tee('myoutput.log'):
        main()
Output:
hello bye
Reply
#4
The wheel has already been invented, and so has logging!

Python has a logging module of course. Look here.

And here.

import logging
 
# Create the file
# and output every level since 'DEBUG' is used
# and remove all headers in the output
# using empty format=''
logging.basicConfig(filename='output.txt', level=logging.DEBUG, format='')
 
logging.debug('Hi')
logging.info('Hello from AskPython')
logging.warning('exit')
file_name = '/home/pedro/temp/atext1.txt'
print('\nHi', file=open(file_name, 'a'))
Reply
#5
(Jun-23-2023, 09:59 PM)Pedroski55 Wrote: The wheel has already been invented, and so has logging!
This is true of course and in general, it is probably better to log than to print. However there is a little difference: in the logging system, you emit logging 'records', there is no way to use the exact semantics of the print() function with its sep and end and flush arguments. So the print function not only outputs information, it also formats the information with lower level details. I don't know how you could plug this semantics to the logging system.
Reply
#6
Simple answer: the OP wanted to log to myoutput.log:

Quote:Assume I want to write something from inside a *.py script to screen AND into file D:\tools\python\myoutput.log
Reply
#7
(Jun-24-2023, 07:37 AM)Pedroski55 Wrote: Simple answer: the OP wanted to log to myoutput.log:
I understand the OP wanted to 'tee' like in the Linux command 'tee' where you just copy the output of a program to other files. I think it all depends on the context and the motivations of this. Tee has its own flexibility.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Why is there an output of None akbarza 1 453 Nov-27-2023, 02:53 PM
Last Post: deanhystad
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,089 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Split pdf in pypdf based upon file regex standenman 1 2,075 Feb-03-2023, 12:01 PM
Last Post: SpongeB0B
  How to split file by same values from column from imported CSV file? Paqqno 5 2,773 Mar-24-2022, 05:25 PM
Last Post: Paqqno
  [split] Results of this program in an excel file eisamabodian 1 1,574 Feb-11-2022, 03:18 PM
Last Post: snippsat
  split txt file data on the first column value shantanu97 2 2,432 Dec-29-2021, 05:03 PM
Last Post: DeaD_EyE
  [split] Help- converting file with pyton script eltomassito 6 3,243 Jul-02-2021, 05:29 PM
Last Post: snippsat
  How do I split the output? AnunnakiKungFu 2 1,779 Feb-25-2021, 11:13 PM
Last Post: AnunnakiKungFu
  Split Characters As Lines in File quest_ 3 2,509 Dec-28-2020, 09:31 AM
Last Post: quest_
  [split] How to convert the CSV text file into a txt file Pinto94 5 3,326 Dec-23-2020, 08:04 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020