Windows Scripting: Capturing Standard Output (Logging)

Previous topic - Next topic

jlpoole

One of the frustrations I have with developing scripts in Scribus 1.5 on Windows is that the standard out has no place to go, unlike Linux where the STDOUT is redirected to the console where Scribus is started.  I therefore came up with the template that allows all prints or write to standard out to continue to go there (wherever that is) and to go to a log file.  I added some functions that wrap "print" and insert a date and time stamp.

Here's the script:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import datetime

try:
    # Please do not use 'from scribus import *' . If you must use a 'from import',
    # Do so _after_ the 'import scribus' and only import the names you need, such
    # as commonly used constants.
    import scribus

except ImportError,err:
    print "This Python script is written for the Scribus scripting interface."
    print "It can only be run from within Scribus."
    sys.exit(1)

class Tee(object):
    """redirect standard output both to 1) standard output and 2) a log file """
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)

#########################
# YOUR IMPORTS GO HERE  #
#########################

def printDt(argv):
    """prints prepending date & time stamp + tab """
    print(datetime.datetime.now().strftime("%m/%d/%Y %I:%M:%S\t") + argv)
   

def printD(argv):
    """prints prepending date & time stamp + space """
    print(datetime.datetime.now().strftime("%m/%d/%Y %I:%M:%S ") + argv)
   
def main(argv):
    """This test the logging to a file.  In Scribus windows, I do not know
       where stdout goes.  In Linux, it usually goes to the terminal
       where Scribus was invoke if done so by a command line. """
    #########################
    #  YOUR CODE GOES HERE  #
    #########################
    #pass    # <--- Delete this line
   
    #
    # Reroute sys.stdout to a file and sys.stdout
    # On Windows Sribus, std.out goes to nowhere, so by having a copy
    # go to a file, I can see what output there.
    # use the SourceForge Tail tools to monitor the file real time.
    #
    logfile = 'C:\scribus_console.log'
    #
    # a = append mode
    # w = overwrite existing file
    #
    f = open(logfile, 'a')
    original = sys.stdout
    sys.stdout = Tee(sys.stdout, f)
    print "test from test_logger.py using print()"  # This will go to stdout and the file
    today = datetime.datetime.now()
    print(today.strftime("%m/%d/%Y %I:%M:%S") + " Here is a log entry with a time & date stamp")
    printD("using printD() auto time/datestamp facility")
    printDt("using printDt() auto time/datestamp facility")
   


def main_wrapper(argv):
    """The main_wrapper() function disables redrawing, sets a sensible generic
    status bar message, and optionally sets up the progress bar. It then runs
    the main() function. Once everything finishes it cleans up after the main()
    function, making sure everything is sane before the script terminates."""
    try:
        scribus.statusMessage("Running Template...")
        scribus.progressReset()
        main(argv)
    finally:
        # Exit neatly even if the script terminated with an exception,
        # so we leave the progress bar and status bar blank and make sure
        # drawing is enabled.
        if scribus.haveDoc():
            scribus.setRedraw(True)
        scribus.statusMessage("")
        scribus.progressReset()

# This code detects if the script is being run as a script, or imported as a module.
# It only runs main() if being run as a script. This permits you to import your script
# and control it manually for debugging.
if __name__ == '__main__':
    if scribus.haveDoc() > 0:
        main_wrapper(sys.argv)
    else:
        messageBox("Stations Create", "You need to have a document open <i>before</i> you can run this script succesfully.", ICON_INFORMATION)
John L. Poole

work: Principal Software Engineer, Oracle Corporation
play: Editions Poole - publisher of classical ensemble piano music (using InDesign & scripts thereunder)

a.l.e

nice hack!

can also be useful on linux, if you have much output and you want to debug it....

jlpoole

I neglected to suggest for windows users: simultaneously running the Tail For Win32 program lets your log file look like a console.
John L. Poole

work: Principal Software Engineer, Oracle Corporation
play: Editions Poole - publisher of classical ensemble piano music (using InDesign & scripts thereunder)

Kunda