I am working in Python and am trying to have a line of code execute and after it executes I am calling sys.exit() to have the script itself "exit." However, it seems that sys.exit() is executing before the line of code above it executes. Below is the code I am trying to implement:
if something == True:
self.redirect('http://www.google.com/')
sys.exit()
The script is exiting before it is redirecting. I need the redirect to complete and then have sys.exit() execute. I CANNOT use the sleep command due to nature of the other code being implemented. Can anyone give me some help as how to fix/workaround this issue?
There is probably some buffering or asynchrony in self.redirect(). People often run into a similar problem when they do a print, followed by sys.exit(): the print output gets buffered, and then the process exits before the in-process output buffer is flushed).
You can work around this by flushing buffers and/or waiting for the asynchronous task to complete.
Its not clear from the question what magic redirect is doing, though.
Try using the atexit module to register a cleanup function to be run just before sys.exit() is called.
To register the redirect function as the cleanup function:
import atexit
atexit.register(redirect, 'http://www.google.com')
Note: the arguments that are passed to the redirect function are included after the function object. We don't need parentheses here because we're passing it the function object, not actually calling the function.
Also, this won't help you if your redirect method is not working properly. I would ensure that your redirect method is working by explicitly calling it from a Python interpreter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With