473,748 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2910
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 PitonEsFacilExc eption(Exceptio n):
"Base class for all Exception of the python es facil code"
pass

class LanguageDoesNot ExistException( PitonEsFacilExc eption):
"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.a ppend(string)
self.content = self.content + string

def display_error(s tr):
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(ke y, 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(ke y, 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 LanguageDoesNot ExistException( lang)

print(string.rj ust("^",e.offse t+3))
return e.text

def display_name_er ror(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(ke y, 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(ke y, langdict[key])
print "NAME ERROR: "+ eerr
elif (plang=="en_py" ):
print "NAME ERROR: " + eerr

else:
raise LanguageDoesNot ExistException( 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_wind ow) + ","
#logrecord += str(code_window ) + "\n"

f=open("log/trials.log", "a")
f.write(logreco rd)
f.close()
def main():
print "Content-type: text/html\n\n"

form = cgi.FieldStorag e()
# 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(ke y, langdict[key])

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

try:
safeeval.safe_e val(code)

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

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

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

outcome = outcome + "," + urllib.quote(ou tput) + "," +
urllib.quote(co de)
add_trial(form, outcome)
def init_dictionary (lang):
if lang == "es->en":
mydict = {'imprime ':'print ','para_cada ':'for ','si ':'if
','en ': 'in ','sino:': 'else:','longit ud(':'len('}
return mydict
elif lang == "en->es":
mydict = {'is not defined':'no esta
definido','name ':'nombre','pri nt ':'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 LanguageDoesNot ExistException( lang)

if __name__ == "__main__":

sys.stderr = sys.stdout
try:
main()
except KeyError,e:
display_error(" Parameter not found in the HTTP request")
except LanguageDoesNot ExistException, e:
display_error(" \"lang\" parameter with value '%s' is not
allowed" % e.lang)
except safeeval.SafeEv alException:
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.quelque ch...@free.quel quepart.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
3847
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 less - during my own installation of Python 2.3 on Fedora Core 1 Linux for a friend of mine). Anyway, HTH, L.
20
5193
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: > > How to find the amount of disk space a user is taking up: > > find / -user rprice -fstype nfs ! -name /dev/\* -ls | awk '{sum+=$7};\ > {print "User rprice total disk use = " sum}'
5
2306
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 fine from the dos shell, but I would really like to work entirely within Emacs. I have two questions: 1) Is it possible to have the *Python Output* in Emacs report the progress during execution? Right now, *Python Output* does not update...
4
9930
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 think to use the text widget. I have no problem to execute the command, but how to display, in a *real-time* fashion the shell retrun?
2
4545
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 the function due to its
3
14903
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( $output ); ?> ...assuming that I don't have an executable called 'lss' on my computer.
14
3373
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 (fr_FR.iso885915), and my terminal (rxvt-unicode) is able to display those chars. What am I missing? Thanks.
3
1469
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
3474
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 do not inherit this value. From "man bash": Shell Variables The following variables are set by the shell:
0
9359
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9310
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9236
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6792
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4592
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2774
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.