Search code examples
pythonpython-2.7python-webbrowser

Difference between os.system and webbrowser


Here are two ways to open a new url on browser using python.

First way is webbrowser module.

webbrowser.open(url)

Another way is os.system(command).

command = "open -a Google\ Chrome url"
os.system(command)

So what's the difference between above ways? And which is faster?

My pc os is macos


Solution

  • webbrowser.open() is a convenient tool for the job, and self-explanatory in the code, so I would use it. It will try to do all the magic for you.
    How fast does it need to be? Do you find yourself opening hundreds of urls at the same time?

    os.system() is a "low-level" command and unless you need power beyond what webbrowser can do, it is easier to get wrong. Unless the command forks/returns immediately (like most browsers will do), it will also wait and hang your script until the command terminates.

    Also it will require the command (open) to be on your PATH (so prefer absolute paths, e.g. /usr/bin/open) and may not always be the one you want, depending on where the script is executed. For example open links to openvt for me, and so would not work for me. (I'd need xdg-open.)

    So webbrowser.open() will be more portable.