473,698 Members | 2,923 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing to stdout and a log file

I would like my 'print' statements to send its output to the user's
screen and a log file.

This is my initial attempt:

class StdoutLog(file) :
def __init__(self, stdout, name='/tmp/stdout.log',
mode='w',bufsiz e=-1):
super(StdoutLog , self).__init__( name,mode,bufsi ze)
self.stdout = stdout
def write(self, data):
self.stdout.wri te(data)
self.write(data )

import sys
sys.stdout = StdoutLog(sys.s tdout)
print 'STDOUT', sys.stdout

When the program is run the string is written to the log file but
nothing appears on my screen. Where's the screen output?

It looks like the superclass's write() method is getting called instead
of the StdoutLog instance's write() method.

The python documentation says 'print' should write to
sys.stdout.writ e() but that doesn't seem to be happening.

Any idea what's going one?
Or ideas on how to debug this?

Thanks, Mike

Jul 19 '05 #1
7 3971
This variation works:
#------------------------------------------------------------------------
class Tee:
def __init__(self, *args):
self.files = args

def write(self, data):
for f in self.files:
result = f.write(data)
return result

def writelines(self , seq):
for i in seq: self.write(i)

import sys
sys.stdout = Tee(sys.stdout, open("/tmp/stdout.log", "w"))

print 'STDOUT', sys.stdout
#------------------------------------------------------------------------

It appears that the 'print' statement always uses file.write if
isinstance(sys. stdout, file). I don't know whether this has been
reported as a bug before, or if there's a reason for the current
behavior. It may be an accidental behavior that is left over from the
days when builtin types were not subclassable.

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFCZaMDJd0 1MZaTXX0RAmdYAJ 9GiKYMT/1HjCfa/8DdpPXNSIvJrACe OOK6
mCfiTD9mqTqNpUu dqvm/Log=
=2JZ/
-----END PGP SIGNATURE-----

Jul 19 '05 #2
Thanks.

I should've mentioned I want StdoutLog to subclass the 'file' type
because I need all the file attributes available.

I could add all the standard file methods and attributes to StdoutLog
without subclassing 'file' but I'd rather avoid this if I can.

Jul 19 '05 #3
In that case, it looks like you won't be able to get what you want
without modifying CPython. PRINT_ITEM calls PyFile_SoftSpac e,
PyFile_WriteStr ing, and PyFile_WriteObj ect, which all use
PyFile_Check(). It might be as simple as changing these to
PyFile_CheckExa ct() calls in PyFile_WriteStr ing / PyFile_WriteObj ect,
but I have no idea whether the test suite still works after this change
is made. It does make this program work (it prints things from X.write):

class X(file):
def write(self, s):
print "X.write", `s`
return file.write(self , s)

import sys
x = X("/tmp/out.txt", "w")
print >>x, 42

I don't care to be the champion of this patch, or to submit it to
sourceforge; I suspect there should be a better review of PyFile_Check
vs PyFile_CheckExa ct uses in fileobject.c, instead of just picking the
few spots that make this usage work. Before being submitted as a patch,
a testcase should be added too. Feel free to run with this if you feel
strongly about it.

Jeff

Index: Objects/fileobject.c
=============== =============== =============== =============== =======
RCS file: /cvsroot/python/python/dist/src/Objects/fileobject.c,v
retrieving revision 2.193
diff -u -u -r2.193 fileobject.c
--- Objects/fileobject.c 7 Nov 2004 14:15:28 -0000 2.193
+++ Objects/fileobject.c 20 Apr 2005 02:41:32 -0000
@@ -2012,7 +2012,7 @@
PyErr_SetString (PyExc_TypeErro r, "writeobjec t with NULL file");
return -1;
}
- else if (PyFile_Check(f )) {
+ else if (PyFile_CheckEx act(f)) {
FILE *fp = PyFile_AsFile(f );
#ifdef Py_USING_UNICOD E
PyObject *enc = ((PyFileObject* )f)->f_encoding;
@@ -2082,7 +2082,7 @@
"null file for PyFile_WriteStr ing");
return -1;
}
- else if (PyFile_Check(f )) {
+ else if (PyFile_CheckEx act(f)) {
FILE *fp = PyFile_AsFile(f );
if (fp == NULL) {
err_closed();
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFCZcHmJd0 1MZaTXX0RAh4eAJ 4wjWlguTzoHWLbj ltZ2f+cXEfa9ACd ErTX
C5ebIIE+I3NrgC3 cIUO9W9o=
=WN4p
-----END PGP SIGNATURE-----

Jul 19 '05 #4
Mike wrote:
I would like my 'print' statements to send its output to the user's
screen and a log file.

This is my initial attempt:

class StdoutLog(file) :
def __init__(self, stdout, name='/tmp/stdout.log',
mode='w',bufsiz e=-1):
super(StdoutLog , self).__init__( name,mode,bufsi ze)
self.stdout = stdout
def write(self, data):
self.stdout.wri te(data) What happens when you do a self.stdout.flu sh() here?
self.write(data )

import sys
sys.stdout = StdoutLog(sys.s tdout)
print 'STDOUT', sys.stdout

When the program is run the string is written to the log file but
nothing appears on my screen. Where's the screen output?

It looks like the superclass's write() method is getting called instead
of the StdoutLog instance's write() method.

The python documentation says 'print' should write to
sys.stdout.writ e() but that doesn't seem to be happening.

Any idea what's going one?
Or ideas on how to debug this?

Thanks, Mike


I had the same problem (writing to file and stdout with print) and my
solution was *not* to subclass file and instead add a
self.outfile=fi le(...) to the constructor.

HTH,
Wolfram
Jul 19 '05 #5
flushing stdout has no effect.

I've got an implementation that does not subclass file. It's not as
nice but it works.

Jul 19 '05 #6
Mike wrote:
I should've mentioned I want StdoutLog to subclass the 'file' type
because I need all the file attributes available.


You might use a surrogate pattern. Here's one I use for this kind of
situation, where I want to subclass but that can't be done for some reason.

class SurrogateNotIni tedError(except ions.AttributeE rror):
pass

class Surrogate(objec t):
def __init__(self, data):
self._data = data

def __getattr__(sel f, name):
if name == "_data":
raise SurrogateNotIni tedError, name
else:
try:
return getattr(self._d ata, name)
except SurrogateNotIni tedError:
raise SurrogateNotIni tedError, name

I'll leave it as an exercise to the reader to make this work when
self._data is actually a list of objects instead of a single object.
You'll obviously need special logic for different methods, like write(),
since for some of them you will want to call every object in self._data,
and others only a single object.
--
Michael Hoffman
Jul 19 '05 #7
Perfect. This is what I"ll use. Thanks! Mike

Jul 19 '05 #8

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

Similar topics

7
7591
by: Paul Watson | last post by:
How can I write lines to stdout on a Windows machine without having '\n' expanded to '\r\n'. I need to do this on Python 2.1 and 2.3+. I see the msvcrt.setmode function. Is this my only path? Is it valid to change the mode of stdout? The file.newlines is not writable.
1
3253
by: Evgeni Sergeev | last post by:
While I can make a verbatim copy of a file like this: file1 = file('ready.pdf', 'rb') file2 = file('out.pdf', 'wb') buffer = file1.read(256) while buffer: file2.write(buffer) buffer = file1.read(256)
6
3495
by: hpy_awad | last post by:
I am writing stings ((*cust).name),((*cust).address)to a file using fgets but rabish is being wrote to that file ? Look to my source please and help me finding the reason why this rabish is being written. /* Book name : File name : E:\programs\cpp\iti01\ch10\ex09_5p1.cpp Program discription: Adding name,Address to customer_record SETUP PROGRAM
25
3900
by: sravishnu | last post by:
Hello, I have written a program to concatanae two strings, and should be returned to the main program. Iam enclosing the code, please give me ur critics. Thanks, main() { char s1,s2; printf("enter first string"); scanf("%s",s1); printf("enter second string");
5
2608
by: =?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7z | last post by:
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__(self, name, mode) self.stdout = sys.stdout sys.stdout = self
4
2236
by: peterv6 | last post by:
I'm having problems writing records to an output file. When I do it in Textpad running on Windows, the output file looks fine. When, however, I copy the script to a Linux machine and use the exact same code, it appends a ^M character on each line written to the file. I have no idea why this is happening. I'm writing to the file by redirecting STDOUT to it. open STDOUT,"> ${output}" || die "$0 can't open $ifile"; This is how I'm...
12
5088
by: hemant.gaur | last post by:
I have an application which writes huge number of bytes into the binary files which is just some marshalled data. int len = Data.size(); //arrary size for (int i = 0; i < len; ++i) fwrite(&Data, 1, 1, f); now after running this for long time and pushing millions of bytes, It once misses writing the last byte of fData. Then the further push of bytes is again correct. As i am not using the return value for the
4
2243
by: pcfreak30 | last post by:
ok, i probably have not been registered here long, but i am no noob. I am very experienced in php, but the php cli is a bit of new territory for me. I am trying to create a simple little script that will fetch a webpage and save it to a file. This is just for practice for the records. here is my code: <?php fwrite(STDOUT,"Created By Derrick Hammer\n");
0
1246
by: xahlee | last post by:
Here's a little tutorial that lets you write emacs commands for processing the current text selection in emacs in your favorite lang. Elisp Wrapper For Perl Scripts http://xahlee.org/emacs/elisp_perl_wrapper.html plain text version follows. ------------------------------------- Elisp Wrapper For Perl Scripts
0
8610
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
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9031
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
7740
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 project—planning, coding, testing, and deployment—without 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...
1
6528
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5862
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
4623
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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
3
2007
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.