Friday, November 1, 2013

Python one-liner to open a web site from the command line

By Vasudev Ram

While importing the antigravity module, I came up with this Python one-liner to open a web site from the command line:

import sys, os.path, webbrowser;"http://" + os.path.splitext(os.path.basename(sys.argv[0]))[0])

If you save the above Python code as, say,, you can run it from the command line with:

where could be any existing site, like,,,, etc. (You have to add the extension .py to the site name to create the file name.)

This should open that web site in your default web browser.

To do the same for other sites, just copy, for example, to .

The content of the file does not need to be edited for different sites, since there is no hard-coding of the site name in the code, only in the file name.

Though I haven't tested this on UNIX or Linux yet, you should be able to make a link from the first site filename to any number of others (one at a time), and achieve the same result as the copy on Windows. The command would be of the form:

$ ln

I also haven't tried the one-liner on UNIX or Linux (yet), but it is likely to work, since the webbrowser module of Python that it uses, is supposed to work there too. But check.

If you like one-liners, you may also find this one (which I wrote a while ago) interesting:

UNIX one-liner to kill a hanging Firefox process

(The comments on that one are also interesting and go into some detail on UNIX processes.)

- Vasudev Ram - Dancing Bison Enterprises

Consulting / training inquiry


Vasudev Ram said...

I put a link to the above post on the Python Reddit, and user SatanKidneyPie said that on Linux, you can use:

xdg-open url

for the same task as the one-liner, i.e. to open a web site from the command line.

Useful to know ...

Vasudev Ram said...

And here is a page about xdg-open.