473,666 Members | 2,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem exiting application in Windows Console.

Ant
Hi all,

I'm putting together a simple help module for my applications, using
html files stored in the application directory somewhere. Basically it
sets up a basic web server, and then uses the webbrowser module to
display it in the users browser. I have it set up to call sys.exit(0)
if the url quit.html is called, but for some reason (on Windows XP via
the cmd.exe shell) python won't let me have the console back. I get the
System Exit stack trace OK:

Exiting...
----------------------------------------
Exception happened during processing of request from ('127.0.0.1',
3615)
Traceback (most recent call last):
....
File "C:\Documen ts and Settings\aroy\M y Do...
sys.exit(0)
SystemExit: 0
----------------------------------------
However, at this point instead of getting back to a command prompt, I
get an unresponsive console. Hitting CTRL-Break gets me the command
prompt back, but I would have expected to get back the command prompt
as soon as the sys.exit(0) had completed.

Here's the code:

import webbrowser, os, sys
from threading import Thread
from BaseHTTPServer import HTTPServer
from SimpleHTTPServe r import SimpleHTTPReque stHandler

class HelpHTTPRequest Handler(SimpleH TTPRequestHandl er):
def do_GET(self):
print "PATH: ", self.path
if self.path.endsw ith("quit.html" ):
print "Exiting... "
sys.exit(0)
else:
return SimpleHTTPReque stHandler.do_GE T(self)

def help(base_dir, server_class=HT TPServer,
handler_class=H elpHTTPRequestH andler):
os.chdir(base_d ir)
server_address = ('', 8000)
httpd = server_class(se rver_address, handler_class)
server_thread = Thread(target=h ttpd.serve_fore ver)
server_thread.s tart()

webbrowser.open ("http://localhost:8000/index.html")

print "Hit CTRL-Break or CTRL-C to exit server"

def main():
current_dir = os.path.split(s ys.argv[0])[0]
help(current_di r)

if __name__ == "__main__":
main()

Nov 8 '06 #1
6 2494
Ant

Ant wrote:
....
However, at this point instead of getting back to a command prompt, I
get an unresponsive console. Hitting CTRL-Break gets me the command
prompt back, but I would have expected to get back the command prompt
as soon as the sys.exit(0) had completed.
....
class HelpHTTPRequest Handler(SimpleH TTPRequestHandl er):
def do_GET(self):
print "PATH: ", self.path
if self.path.endsw ith("quit.html" ):
print "Exiting... "
sys.exit(0)
else:
return SimpleHTTPReque stHandler.do_GE T(self)

def help(base_dir, server_class=HT TPServer,
handler_class=H elpHTTPRequestH andler):
....

OK, I've narrowed the problem back to the way HTTPServer (actually its
TCPServer parent) handles exceptions thrown by the process_request
method by catching them all, and then calling a handle_error method.
There doesn't seem to be a way of getting at the exception thrown
however - does anyone know how I can get this information?

The default handle_error method in the TCPServer uses the traceback
module to print the stacktrace, but I can't find anything in that
module to get the actual exception object (or string) - is there an
alternative trick?

Incidentally, this seems to me to be a pretty drastic try: except:
block, catching *everything* and then (essentially) discarding the
exception. Wouldn't it be better to either catch only the exceptions
that are expected (presumably IO errors, Socket exceptions, HTTP error
code exceptions etc), and let others pass through, or alternatively
pass the exception through to the handle_error() method since this is
where it should be dealt with?

Thanks.

Nov 8 '06 #2
Ant

Ant wrote:
....
OK, I've narrowed the problem back to the way HTTPServer (actually its
TCPServer parent) handles exceptions thrown by the process_request
method by catching them all, and then calling a handle_error method.
There doesn't seem to be a way of getting at the exception thrown
however - does anyone know how I can get this information?
Hmm. Lonely topic ;-)

I've found a way to solve the problem, by creating a subclass of
HTTPServer which overrides the handle_error method:

class HelpServer(HTTP Server):
def handle_error(se lf, request, client_address) :
exception_line = inspect.trace()[-1][-2][0]
if "sys.exit" in exception_line:
print "Trying to exit again!"
sys.exit(0)
else:
HTTPServer.hand le_error(self, request, client_address)

This seems a really nasty hack though - any ideas for a cleaner way to
do it?

Nov 8 '06 #3
Ant wrote:
Ant wrote:
....
>OK, I've narrowed the problem back to the way HTTPServer (actually its
TCPServer parent) handles exceptions thrown by the process_request
method by catching them all, and then calling a handle_error method.
There doesn't seem to be a way of getting at the exception thrown
however - does anyone know how I can get this information?

Hmm. Lonely topic ;-)

I've found a way to solve the problem, by creating a subclass of
HTTPServer which overrides the handle_error method:

class HelpServer(HTTP Server):
def handle_error(se lf, request, client_address) :
exception_line = inspect.trace()[-1][-2][0]
if "sys.exit" in exception_line:
print "Trying to exit again!"
sys.exit(0)
else:
HTTPServer.hand le_error(self, request, client_address)

This seems a really nasty hack though - any ideas for a cleaner way to
do it?
First of all, five hour response time is a high expectation, you must be
a Platinum customer :-)

Secondly, while a try/except catching all exceptions *is* unusual it's
justifiable in a server context (though some logging and/or analysis
certainly wouldn't go amiss).

Thirdly your "ugly hack" *could* be replaced by something cleaner with
more analysis of the trace structure, but given how infrequently this
code is going to run and the low probability that anything else will
trigger the hook I'd be happy with it as it is. But that's just me ...

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Nov 8 '06 #4
This seems a really nasty hack though - any ideas for a cleaner way to
do it?
You could overload handle_request instead. I think that makes more
sense anyway because you don't want to handle a SystemExit exception as
an error, you want to exit. Of course this only deals with catching the
exception, there may be a better method of shutting down and exiting
the server (other than sys.exit that is).

class HelpServer(HTTP Server):
def handle_request( self):
try:
request, client_address = self.get_reques t()
except socket.error:
return
if self.verify_req uest(request, client_address) :
try:
self.process_re quest(request, client_address)
except SystemExit:
raise SystemExit
except:
self.handle_err or(request, client_address)
self.close_requ est(request)

Nov 8 '06 #5
At Wednesday 8/11/2006 09:10, Ant wrote:

[getting a stack trace for SystemExit instead of a clean exit]
>class HelpHTTPRequest Handler(SimpleH TTPRequestHandl er):
def do_GET(self):
print "PATH: ", self.path
if self.path.endsw ith("quit.html" ):
print "Exiting... "
sys.exit(0)
else:
return SimpleHTTPReque stHandler.do_GE T(self)

def help(base_dir, server_class=HT TPServer,
handler_class= HelpHTTPRequest Handler):
os.chdir(base_d ir)
server_address = ('', 8000)
httpd = server_class(se rver_address, handler_class)
server_thread = Thread(target=h ttpd.serve_fore ver)
server_thread.s tart()

webbrowser.open ("http://localhost:8000/index.html")

print "Hit CTRL-Break or CTRL-C to exit server"
Replace serve_forever with your own loop checking an exit flag, and
set the flag in your "quit.html" handler instead of sys.exit(0)
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 8 '06 #6
Ant
Steve Holden wrote:
....
First of all, five hour response time is a high expectation, you must be
a Platinum customer :-)
I'm in the last week of my current job - start a new one on Monday, and
so I haven't got a great deal to do at the moment. Five hours is a
lifetime when you're staring at a newsgroup waiting for it to change
;-)
Secondly, while a try/except catching all exceptions *is* unusual it's
justifiable in a server context (though some logging and/or analysis
certainly wouldn't go amiss).
True. And I'd expected that the exception ought to be passed to the
handle_error method so that something could be done with it there. This
morning however I discovered that Guido's been in his time machine
since yesterday and provided the very useful sys.exc_info() function
for this very purpose!
Thirdly your "ugly hack" *could* be replaced by something cleaner with
more analysis of the trace structure, but given how infrequently this
code is going to run and the low probability that anything else will
trigger the hook I'd be happy with it as it is. But that's just me ...
The sys.exc_info() was what I was looking for it turns out, I can get
the exception type from that instead of trying to parse the stack
trace.

However:

Gabriel Genellina wrote:
....
Replace serve_forever with your own loop checking an exit flag, and
set the flag in your "quit.html" handler instead of sys.exit(0)
This is the approach I decided to go for. I found that RequestHandler
objects have a reference to its server that I can use to control the
server.

Thanks for the input chaps!

Nov 9 '06 #7

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

Similar topics

0
1286
by: Linesh Gajera | last post by:
Hi, I have unique problem. I have configured RemotingServer running as Console Application and my Remoting object access Oracle database. My remoting object make call to Oracle database and returns result if i run RemotingServer as Console Application. Then i configured RemotingServer as Windows Service. My Windows Service starts fine, it also configured Remoting Channels as well. Now problem is remoting object makes call to oracle...
4
1730
by: wobbles | last post by:
Hi Everyone, I've spent hours investigating why my Async (one way) call wasn't invoking the method on my server. Basically, if I remove " Console.ReadLine() ", the method DOESN'T get invoked. Can anyone tell me why? Does the call require a pause? (ErrorInformation is a serializable struct - for those who are
5
11230
by: Barry Mossman | last post by:
Hi, can I detect whether my class is running within the context of a Console application, vs say a WinForm's application ? also does anyone know whether the compiler or runtime is smart enough to avoid the overhead of writing to the console if it is not visible, eg I am running inside a WinForm application. thanks
1
3174
by: Charles | last post by:
I'm trying to write a windows application in C# (Using Microsoft Visual C# 2005 Express) that is nothing more than a simple UI with buttons on it. The buttons do various things like running programs and executing registry entries. The majority of my buttons work however, I have come upon a problem. I need a few of the buttons to run DOS batch files, the batch files in turn run program installers (specifically windows update runtime .exe...
6
3676
by: GL | last post by:
I am getting a crash while exiting from my application. Pl find the Stack Trace of the crash: System.Windows.Forms.Application.ThreadWindows.ThreadWindows(System.Windows.Forms.Control parent = <undefined value>, bool onlyWinForms = true) + 0x8c bytes system.windows.forms.dll!ThreadContext.DisposeThreadWindows() + 0x54 bytes system.windows.forms.dll!ThreadContext.Dispose() + 0xa1 bytes...
15
2399
by: Ron L | last post by:
We are working on a distributed VB.Net application which will access a SQL database located on a known server. Each client will run on the user's local machine. To implement this, we are trying to use remoting for our access to the SQL server, with the remoting being via IIS. Since all of our users will have accounts in the destination domain, we want to have IIS handle the security for us and not allow anonymous. We have set this up...
7
4382
by: Terry Olsen | last post by:
I've used the following suggestion from one of the MVP's here: 'Add a reference to 'System.Windows.Forms.dll', import the ''System.Windows.Forms' namespace, and call 'Application.Run' at the end of 'your 'Sub Main'. Then you can call 'Application.ExitThread' to quit the 'application. Is there a way I can prompt for confirmation before allowing the console app to exit? And abort the termination if necessary?
5
3852
by: Tim Werth | last post by:
I have a .NET console application that is kicked off by a .NET Windows service. They communicate via .NET Remoting, although there isn't much communication between the two while the console app is running. There can be, and are typically, several instances of the console app running at the same time communicating back to the service. The console app creates a delegate to do some work while the main thread waits on a ManualResetEvent to...
2
2626
by: dc | last post by:
I have a baffling connection problem from my C# console app to a sql server express database. The console application opens the sql database using the following code:- vDataSource = "server = " + vgSqlServer + "; " + "database = " + vgSqlServerDb + ";" + "uid = XXX; pwd = XXX; ";
0
8444
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8781
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
8551
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
8639
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
6198
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
4198
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
4368
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1775
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.