Using os.startfile and webbrowser.open in ArcGIS for Desktop

os.startfile and webbrowser.open are two very useful functions in the Python library. However, due to some conflicts in the way the Windows libraries expect to be called, they can fail or crash when called within ArcGIS for Desktop in an add-in script or geoprocessing script tool (see the Remarks section on this MSDN reference page).

import functools
import os
import threading
import webbrowser

# A decorator that will run its wrapped function in a new thread
def run_in_other_thread(function):
    # functool.wraps will copy over the docstring and some other metadata
    # from the original function
    @functools.wraps(function)
    def fn_(*args, **kwargs):
        thread = threading.Thread(target=function, args=args, kwargs=kwargs)
        thread.start()
        thread.join()
    return fn_

# Our new wrapped versions of os.startfile and webbrowser.open
startfile = run_in_other_thread(os.startfile)
openbrowser = run_in_other_thread(webbrowser.open)

The local functions startfile and openbrowser will be made available, which have the same parameters as the versions in the standard library but will run in another thread and therefore work as expected.

Leave a comment