Search code examples
pythonpython-webbrowser

Run a webbrowser and continue script without close the browser


I need help with this code:

import webbrowser

chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open('https://www.google.com/')
print('test browser')

it open chrome and visit the website, but don't print until I close the browser.

If I use this one:

import webbrowser

webbrowser.open('https://www.google.com/')
print('test browser')

It run default browser(brave), visit the website and print correctly.

How can I run X browser and print without need of close it to continue script?


Solution

  • You could create a new Thread and in that thread open the browser:

    from threading import Timer
    
    def open_browser():
        webbrowser.open('https://www.google.com/')
    
    Timer(1, open_browser).start()
    print(“test”)
    

    Everything that has to do with interaction of the browser should now be placed in def open_browser():

    This code will set a timer for 1 millisecond and then execute the function within a seperate thread, so your code keeps executing.