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; webbrowser.open("http://" + os.path.splitext(os.path.basename(sys.argv[0]))[0])

If you save the above Python code as, say, a.site.com.py, you can run it from the command line with:
C:> a.site.com.py

where a.site.com could be any existing site, like ibm.com, oreilly.com, python.org, mit.edu, 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, ibm.com.py to python.org.py .

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 ibm.com.py python.org.py

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




DiscountMags.com


2 comments:

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.