print to stdout and to a log file.....

Alex Martelli alex at magenta.com
Mon Aug 21 09:18:22 EDT 2000


"Amir Mistric" <amir.mistric at usa.net> wrote in message
news:Ft9o5.1806$p36.418637 at news2.mia...
> Hi
> If I have a command
> os.system("program.exe %s %s" %(file1,file2))
> how can I capture the output of this execution to both stdout and to a
lets
> say log file.....

On any Unix-like system, that's what the program tee does for you:

    os.system("program.exe %s %s | tee %s" % (file1, file2, logfilename))

This is quite independent from Python and works at the OS level.

Unfortunately, from the .EXE extension, it seems you're not working
under any Unix-like system but rather on Windows, NT, Dos, or so.

If so, then...:


> log_detail = os.popen("program.exe %s %s" %(file1,file2))
> LogFile.write("%s" % log_detail.read())
>
> but this did not write output to neither stdout nor my log file......

...I've heard that os.popen may not be reliable on the 1.5.2 (and earlier?)
Python release on Windows.  Fortunately, if you download and install
Hammond's "win32all" windows-extensions, this will give you a win32
Python module whose win32.popen implementation IS reliable on Windows,
so you can use exactly this approach.


> Also another question I have is :
> Is it possible to have one print statement that wil write to stdout and to
a
> file? For example:
> print "---------------------------------------------------------"
>
LogFile.write("---------------------------------------------------------\n")
>
> Can this be accomplished in some other fashion where only one line of code
> can be written????

Yes, prepare a small object which does exactly this:

class tee:
    def __init__(self, *fileobjects):
        self.fileobjects=fileobjects
    def write(self, string):
        for fileobject in self.fileobjects:
            fileobject.write(string)

Now just instantiate, and install as sys.stdout, a suitably initialized
instance of this class:

    sys.stdout = tee(sys.stdout, LogFile)

and you're done -- remember to save what used to be in sys.stdout if you
also want to remove this later (by just assigning to sys.stdout what was
in it before; as it happens, with this implementation you could use:
    sys.stdout = sys.stdout.fileobjects[0]
but this may not be considered very readable or reliable).


Alex






More information about the Python-list mailing list