display messages in python shell

jose Barcelona josetokyo at gmail.com
Tue Nov 20 08:11:32 EST 2007


Hi Kou,

  I use this in http://cern.ch/test-volunteers...
  to redirect error messages... \etc
  hope it helps

#!/usr/bin/python
import os
import cgi
import safeeval
import sys
import string
import time
import re
import urllib

class PitonEsFacilException(Exception):
    "Base class for all Exception of the python es facil code"
    pass

class LanguageDoesNotExistException(PitonEsFacilException):
    "Exception raised in case the received 'lang' parameter is non of
'en' or 'es'"
    def __init__(self, lang):
        self.lang=lang

class WritableObject:
    def __init__(self):
        self.content = ""
    def write(self, string):
        #self.content.append(string)
        self.content = self.content + string

def display_error(str):
    print "%s" % str
    sys.exit(0)


def display_syntax_error(e,plang):
    if (plang=="es_pi"):
	eerr = e.text.replace("\n","")
	langdict = init_dictionary("en->es")
	for key in langdict:
		eerr = eerr.replace(key, langdict[key])
    	print("ERROR SINTACTICO")
        print("Revise la linea %s" % e.lineno)
        print("   %s " % eerr)
    elif (plang=="en_pi"):
	eerr = e.text.replace("\n","")
	langdict = init_dictionary("en->es en_pi")
	for key in langdict:
		eerr = eerr.replace(key, langdict[key])
    	print("SYNTAX ERROR")
        print("Chec kline %s" % e.lineno)
        print("   %s " % eerr)
    elif (plang=="en_py"):
        print("SYNTAX ERROR")
        print("Check line %s" % e.lineno)
        print("   %s " % e.text.replace("\n",""))
    else:
        raise LanguageDoesNotExistException(lang)

    print(string.rjust("^",e.offset+3))
    return e.text

def display_name_error(e,plang):

    saveout = sys.stdout
    foo = WritableObject()    # a writable object
    sys.stdout = foo
    print e
    sys.stdout = saveout

    eerr = foo.content

    if (plang=="es_pi"):
	langdict = init_dictionary("en->es")
	for key in langdict:
		eerr = eerr.replace(key, langdict[key])
        print "ERROR DE NOMRE: "+ eerr
    elif (plang=="en_pi"):
	langdict = init_dictionary("en->es en_pi")
	for key in langdict:
		eerr = eerr.replace(key, langdict[key])
        print "NAME ERROR: "+ eerr
    elif (plang=="en_py"):
        print "NAME ERROR: " + eerr

    else:
        raise LanguageDoesNotExistException(lang)

    return foo.content

def add_trial(form, outcome):
    email = form["email"].value
    code = form["code"].value
    now = time.time()
    logrecord = email + ","
    logrecord += str(now) + ","
    logrecord += time.strftime("%Y/%m/%d %H:%M:%S %Z",
time.localtime(now)) + ","
    logrecord += str(outcome) + "\n"
    #logrecord += str(output_window) + ","
    #logrecord += str(code_window) + "\n"

    f=open("log/trials.log", "a")
    f.write(logrecord)
    f.close()


def main():


    print "Content-type: text/html\n\n"

    form = cgi.FieldStorage()
    # print form.keys()

    code = form["code"].value
    lang = form["lang"].value
    plang = form["plang"].value

    outcome="nodef"
    output="nodef"

    if (plang=="es_pi" or plang =="en_pi"):
	langdict = init_dictionary("es->en")
	for key in langdict:
		code = code.replace(key, langdict[key])

    if code.count("\r\n") > 0:
       code = code.replace("\r\n","\n")

    try:
	safeeval.safe_eval(code)

        saveout = sys.stdout
    	# example with redirection of sys.stdout
	foo = WritableObject()    # a writable object
	sys.stdout = foo
        safeeval.safe_eval(code)
	output = foo.content
	sys.stdout = saveout

    except SyntaxError,e:
        output = display_syntax_error(e,plang)
	outcome = "XS"

    except NameError,e:
        output = display_name_error(e,plang)
	outcome = "XN"

    outcome = outcome + "," + urllib.quote(output)  + "," +
urllib.quote(code)
    add_trial(form,outcome)


def init_dictionary(lang):
    if lang == "es->en":
        mydict = {'imprime ':'print ','para_cada ':'for ','si ':'if
','en ': 'in ','sino:': 'else:','longitud(':'len('}
        return mydict
    elif lang == "en->es":
        mydict = {'is not defined':'no esta
definido','name':'nombre','print ':'imprime ','for ':'para_cada ','if
':'si ','in ': 'en ','else:': 'sino:','len': 'longitud('}
        return mydict
    elif lang == "en->es en_pi":
        mydict = {'print ':'imprime ','for ':'para_cada ','if ':'si
','in ': 'en ','else:': 'sino:','len': 'longitud('}
        return mydict

    raise LanguageDoesNotExistException(lang)

if __name__ == "__main__":

    sys.stderr = sys.stdout
    try:
        main()
    except KeyError,e:
        display_error("Parameter not found in the HTTP request")
    except LanguageDoesNotExistException, e:
        display_error("\"lang\" parameter with value '%s' is not
allowed" % e.lang)
    except safeeval.SafeEvalException:
        display_error("SafeEvalError, This is a place holder for not
allowed usage of methods")
    except SyntaxError,e:
        display_error(e)
    except Exception,e:
        display_error(e)



On Nov 19, 8:09 pm, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> Jens a écrit :
>
> > On 19 Nov., 19:48, kou... at hotmail.com wrote:
>
> >>Is it possible to display messages in the python shell?  I want to

> >>display error messages based on parameters in my scripts to the
> >>users.  Is there another way to display messages other than log
> >>files?  Thanks.
>
> >>Kou
>
> > What about using print? For example:
>
> > print "This is a message."
>
> print writes to stdout - which is for normal program outputs. wrt/
> errors, you want stderr, ie:
>
> import sys
>
> print >> sys.sdterr, "this is an error message"
>
> HTH




More information about the Python-list mailing list