Selenium: Quit Python script without closing browser
Asked Answered
B

1

8

I use the following to handle the situation where Ctrl + C is used to terminate a running Python script.

except KeyboardInterrupt:
    print "ABORTED"

However, this also terminates my Selenium WebDriver browser.

Is there a way to terminate the script and keep the browser alive, so that I can continue using it?

What I usually do instead, is to pause the script via Ctrl + Z. This unfortunately often causes the browser to freeze and not respond.

Barca answered 31/3, 2016 at 13:32 Comment(4)
so just don't call driver.quit() right?Endometrium
@ChrisHawkes, I think OP doesn't use driver.quit(). sys.exit() close browser session despite of calling driver.quit()Mckale
@Mckale True, although I don't think it matters if sys.exit() is in there because Ctrl+C will make everything exit anyway.Barca
just don't call driver.quit() or sys.exit()Endometrium
M
5

You can replace CTRL+C+sys.exit() with quit() method to terminate Python script without closing browser session. Just use following form:

user_choice = raw_input('Please click ENTER button to close application')
if not user_choice:
    print "ABORTED"
    quit()
Mckale answered 31/3, 2016 at 13:52 Comment(4)
Why you use ctrl+C? Is it mandatory for you to end script this way?Mckale
Well, I guess it's not mandatory to use Ctr+C. If another keypress can be intercepted during the script run, then the problem could be avoided.Barca
You can close it by pressing Enter. Check updated answerMckale
If the script is looping, you can't just wait for user inputJansenism

© 2022 - 2024 — McMap. All rights reserved.