473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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',bufsize=-1):
super(StdoutLog, self).__init__(name,mode,bufsize)
self.stdout = stdout
def write(self, data):
self.stdout.write(data)
self.write(data)

import sys
sys.stdout = StdoutLog(sys.stdout)
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.write() 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 3951
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)

iD8DBQFCZaMDJd01MZaTXX0RAmdYAJ9GiKYMT/1HjCfa/8DdpPXNSIvJrACeOOK6
mCfiTD9mqTqNpUudqvm/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_SoftSpace,
PyFile_WriteString, and PyFile_WriteObject, which all use
PyFile_Check(). It might be as simple as changing these to
PyFile_CheckExact() calls in PyFile_WriteString / PyFile_WriteObject,
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_CheckExact 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_TypeError, "writeobject with NULL file");
return -1;
}
- else if (PyFile_Check(f)) {
+ else if (PyFile_CheckExact(f)) {
FILE *fp = PyFile_AsFile(f);
#ifdef Py_USING_UNICODE
PyObject *enc = ((PyFileObject*)f)->f_encoding;
@@ -2082,7 +2082,7 @@
"null file for PyFile_WriteString");
return -1;
}
- else if (PyFile_Check(f)) {
+ else if (PyFile_CheckExact(f)) {
FILE *fp = PyFile_AsFile(f);
if (fp == NULL) {
err_closed();
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFCZcHmJd01MZaTXX0RAh4eAJ4wjWlguTzoHWLbjltZ2f +cXEfa9ACdErTX
C5ebIIE+I3NrgC3cIUO9W9o=
=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',bufsize=-1):
super(StdoutLog, self).__init__(name,mode,bufsize)
self.stdout = stdout
def write(self, data):
self.stdout.write(data) What happens when you do a self.stdout.flush() here?
self.write(data)

import sys
sys.stdout = StdoutLog(sys.stdout)
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.write() 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=file(...) 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 SurrogateNotInitedError(exceptions.AttributeError) :
pass

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

def __getattr__(self, name):
if name == "_data":
raise SurrogateNotInitedError, name
else:
try:
return getattr(self._data, name)
except SurrogateNotInitedError:
raise SurrogateNotInitedError, 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
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?...
1
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 =...
6
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...
25
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;...
5
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...
4
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...
12
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)...
4
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...
0
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.