开发者

sys.exit() terminates too quickly?

开发者 https://www.devze.com 2023-04-12 02:45 出处:网络
I\'m running some code with a sys.exit() call at the end. Without the sys.exit() line, the self.response works just fine and renders the template. But when I call sys.exit(), the page returns blank. I

I'm running some code with a sys.exit() call at the end. Without the sys.exit() line, the self.response works just fine and renders the template. But when I call sys.exit(), the page returns blank. It's almost like sys.exit() is interrupting the template mid-render. Why is it doing this?

page = 'index.html'
template_values = {}
path = os.path.join(os.path.dirname(__file__), page)
self.response.out.write(template.render(path, template_values))
sys.exit()

ED开发者_JAVA百科IT I've solved my problem by using "return" instead of "sys.exit()"


Remove the sys.exit().

If you're basing it on the wording in http://code.google.com/appengine/docs/python/runtime.html#Responses (which has since been reworded), pretend for the moment that the use of "exit" in the first two sentences means "completes" or "finishes".


As others have already given good solutions, I'll try to explain why this happens.

The SystemExit exception raised by sys.exit() differs from other exceptions in one particullar way. If it isn't caught, sys.excepthook isn't called. Instead, after printing the message contained within it and extracting the exit reason, Python shuts down (Py_Finalize) and calls the ANSI/C function exit() which terminates the process.

A solution is to either let the process end normally (see other answers) or to flush the streams.


Alternatively, you can catch SystemExit and return normally:

def main():
 try:
   ...
 except SystemExit, e:
   # return normally for exit() or exit(0). Otherwise, reraise.
   if e.args and e.args[0]:
     raise

Expanding slightly:

The reason it doesn't work is that your Python script isn't being run like a "normal" CGI — there's an exception-catching wrapper, among other things, and sys.exit() is implemented by raising an exception (which doesn't subclass Exception() so it doesn't get caught by default).

I consider this a bug in GAE; you might want to file a bug report. (OTOH, you really shouldn't be using sys.exit() within GAE, since then it's unclear whether your main() function is re-runnable.)


Try flushing the buffer before the sys.exit call:

page = 'index.html'
template_values = {}
path = os.path.join(os.path.dirname(__file__), page)
self.response.out.write(template.render(path, template_values))
self.response.out.flush()
sys.exit()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号