473,656 Members | 2,777 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Issue of redirecting the stdout to both file and screen

I wanna print the log to both the screen and file, so I simulatered a
'tee'

class Tee(file):

def __init__(self, name, mode):
file.__init__(s elf, name, mode)
self.stdout = sys.stdout
sys.stdout = self

def __del__(self):
sys.stdout = self.stdout
self.close()

def write(self, data):
file.write(self , data)
self.stdout.wri te(data)

Tee('logfile', 'w')
print >>sys.stdout, 'abcdefg'

I found that it only output to the file, nothing to screen. Why?
It seems the 'write' function was not called when I *print* something.

May 28 '07 #1
5 2604
人言落日是 天涯,望极 天涯不见家 wrote:
I wanna print the log to both the screen and file, so I simulatered a
'tee'

class Tee(file):

def __init__(self, name, mode):
file.__init__(s elf, name, mode)
self.stdout = sys.stdout
sys.stdout = self

def __del__(self):
sys.stdout = self.stdout
self.close()

def write(self, data):
file.write(self , data)
self.stdout.wri te(data)

Tee('logfile', 'w')
print >>sys.stdout, 'abcdefg'

I found that it only output to the file, nothing to screen. Why?
It seems the 'write' function was not called when I *print* something.
There are places in the C code of Python that do the equivalent of

if isinstance(file _like_object, file):
file.write(file _like_object, text)
else:
file_like_objec t.write(text)

Therefore you can't safely inherit from file. The workaround is to make your
own file-like object; yours would become

class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close ()
def write(self, data):
self.file.write (data)
self.stdout.wri te(data)

Peter
May 28 '07 #2
En Mon, 28 May 2007 06:17:39 -0300, 人言落日是 天涯,望极 天涯不见家
<ke********@gma il.comescribió :
I wanna print the log to both the screen and file, so I simulatered a
'tee'

class Tee(file):

def __init__(self, name, mode):
file.__init__(s elf, name, mode)
self.stdout = sys.stdout
sys.stdout = self

def __del__(self):
sys.stdout = self.stdout
self.close()

def write(self, data):
file.write(self , data)
self.stdout.wri te(data)

Tee('logfile', 'w')
print >>sys.stdout, 'abcdefg'

I found that it only output to the file, nothing to screen. Why?
It seems the 'write' function was not called when I *print* something.
You create a Tee instance and it is immediately garbage collected. I'd
restore sys.stdout on Tee.close, not __del__ (you forgot to call the
inherited __del__ method, btw).
Mmm, doesn't work. I think there is an optimization somewhere: if it looks
like a real file object, it uses the original file write method, not yours.
The trick would be to use an object that does NOT inherit from file:

import sys
class TeeNoFile(objec t):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def close(self):
if self.stdout is not None:
sys.stdout = self.stdout
self.stdout = None
if self.file is not None:
self.file.close ()
self.file = None
def write(self, data):
self.file.write (data)
self.stdout.wri te(data)
def flush(self):
self.file.flush ()
self.stdout.flu sh()
def __del__(self):
self.close()

tee=TeeNoFile(' logfile', 'w')
print 'abcdefg'
print 'another line'
tee.close()
print 'screen only'
del tee # should do nothing

--
Gabriel Genellina

May 28 '07 #3
Gabriel Genellina wrote:
En Mon, 28 May 2007 06:17:39 -0300, ???????????????
<ke********@gma il.comescribi:
>I wanna print the log to both the screen and file, so I simulatered a
'tee'

class Tee(file):

def __init__(self, name, mode):
file.__init__(s elf, name, mode)
self.stdout = sys.stdout
sys.stdout = self

def __del__(self):
sys.stdout = self.stdout
self.close()

def write(self, data):
file.write(self , data)
self.stdout.wri te(data)

Tee('logfile ', 'w')
print >>sys.stdout, 'abcdefg'

I found that it only output to the file, nothing to screen. Why?
It seems the 'write' function was not called when I *print* something.

You create a Tee instance and it is immediately garbage collected.
It is not garbage collected until the next assignment to sys.stdout.

Peter

May 28 '07 #4
En Mon, 28 May 2007 09:10:40 -0300, Peter Otten <__*******@web. de>
escribi:
Gabriel Genellina wrote:
>En Mon, 28 May 2007 06:17:39 -0300, ???????????????
<ke********@gm ail.comescribi :
>> def __init__(self, name, mode):
file.__init__(s elf, name, mode)
self.stdout = sys.stdout
sys.stdout = self

Tee('logfile' , 'w')
print >>sys.stdout, 'abcdefg'

I found that it only output to the file, nothing to screen. Why?
It seems the 'write' function was not called when I *print* something.

You create a Tee instance and it is immediately garbage collected.

It is not garbage collected until the next assignment to sys.stdout.
Yes, sorry, this was my first guess. Later I discovered the real reason
-you pointed it too-, I should have removed the whole first paragraph on
my reply.

--
Gabriel Genellina

May 28 '07 #5
I see. Many thanks to you!

May 29 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
6302
by: Alexander Stippler | last post by:
Hi, The short story: I have to redirect stdout (not cout!!) to an ostream. How can I manage this? The long story: I use the NAGC numerics library with C++ and want to use its output routines for e.g. complex matrices. The problem: You can either print to a file (given by filename) or to stdout. To call the NAGC-method within an operator<< thus I have to redirect stdout to the given
2
11070
by: Jason Heyes | last post by:
Here is what I use to redirect printed messages to a file: std::ofstream file("logfile"); std::cout.rdbuf(file.rdbuf()); std::cout << "this message goes to a file" << std::endl; Will the next message I print go to a file as well? std::printf("does this message go to a file?");
8
5778
by: Morpheus | last post by:
I am trying to test a function that outputs text to the standard output, presumably using a cout call. I do not have access to the source, but need to test the output. Is this possible? I can technically create an executable that calls the function and then using a command prompt call the exexutable using the > output.txt redirector but I would prefer to do everything within the application itself. Is there a way for force an output...
13
2693
by: souissipro | last post by:
Hi, I have written a C program that does some of the functionalities mentionned in my previous topic posted some days ago. This shell should: 1- execute input commands from standard input, and also from a file conatining the commands 2- does the redirection of the input and output from and to files. 3- retrieve the environment variables like HOME,..
1
2584
by: pp4175 | last post by:
Hello Everyone, I am currently working on writing a GUI wrapper for a Menu driven DOS Program. What I was looking on doing is redirecting stdout/stdin to a stream and read/write similar to a file. My issue is that I try to read from the stdout stream and never get anything only if the program has exited. Is there a way of reading the redirected stdout from a DOS program in say real time? I have tried the async (BeginOutputReadLine) and...
10
7621
by: SamG | last post by:
How could i make, from inside the program, to have the stdout and stderr to be printed both to a file as well the terminal(as usual).
3
2108
by: pnsreee | last post by:
Hi All, I am trying to print a log file created in the same script with the code bellow. but Im not getting output on screen. The output file is created using rediretion of output. open(STDOUT, ">flat.log") || die "Can't redirect stdout"; prinf " ----------------------------------------------\n";
0
1822
by: Tom Gaudasinski | last post by:
Greetings, I'm trying to redirect python's stdout to another location. The reason for this is that I'm embedding python in an application. Now, originally my code was developed for Linux and that did not require redirection due to the fact that every X11 application can have an STDOUT associated with it. I then proceeded to take interest in making my code portable and looked at compiling it on windows, however Win32 GUI applications are...
7
7157
by: Cell | last post by:
when both are connected to screen and the anything written to these two constant file pointers will go onto the screen ?
0
8382
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8717
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8600
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7311
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5629
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1600
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.