473,387 Members | 1,619 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,387 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 2891
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

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.