473,233 Members | 1,448 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,233 software developers and data experts.

display messages in python shell

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
Nov 19 '07 #1
3 2882
On 19 Nov., 19:48, kou...@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."
Nov 19 '07 #2
Jens a écrit :
On 19 Nov., 19:48, kou...@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
Nov 19 '07 #3
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(PitonEsFacilExceptio n):
"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...@free.quelquepart.frwrote:
Jens a écrit :
On 19 Nov., 19:48, kou...@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
Nov 20 '07 #4

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

Similar topics

4
by: Logan | last post by:
Several people asked me for the following HOWTO, so I decided to post it here (though it is still very 'alpha' and might contain many (?) mistakes; didn't test what I wrote, but wrote it - more or...
20
by: Matthew Thorley | last post by:
My friend sent me an email asking this: > I'm attemtping to decide which scripting language I should master and > was wondering if it's possible to do > these unixy awkish commands in python:...
5
by: Darren Dale | last post by:
I am using Emacs Python mode, and my project involves reading large datafiles and processing large arrays. I have some code that reports the progress during these time consuming processes. It works...
4
by: Yann.K | last post by:
Hello. Using Tkinter, i would create a widget which display a shell command return. This return is long, and i would display a real time display (like with the tail -f commande on Linux) I...
2
by: Xah Lee | last post by:
Python Doc Problem Example: os.system Xah Lee, 2005-09 today i'm trying to use Python to call shell commands. e.g. in Perl something like output=qx(ls) in Python i quickly located the...
3
by: Robert S | last post by:
I would like to display error messages put out by shell commands. For example the following code gives no output and the array $output has no values: <?php exec( 'lss', $output ); var_dump(...
14
by: Fabrice DELENTE | last post by:
Hello. I'm trying to display french characters (è -- that's e grave -- or à -- agrave) in python 2.5, with the ncurses wrapper that comes it, and I can't. My locale is set correctly...
3
by: wxPythoner | last post by:
This really looks ugly for an error message: + Stopped python Please explain to me the role of the '+' sign. And why is there such a gap between 'Stopped' and 'python'?
0
by: Cameron Simpson | last post by:
On 17Aug2008 21:25, John Nagle <nagle@animats.comwrote: Because $HOSTNAME is a bash specific variable, set by bash but NOT EXPORTED! Like $0 and a bunch of other "private" variables, subprocesses...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.