04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

218 CHAPTER 10 ■ BATTERIES INCLUDED<br />

Example<br />

Starting a Web browser. The system command can be used to execute any external program, which is very useful<br />

in environments such as UNIX where you can execute programs (or commands) from the command line to list the<br />

contents of a directory, send e-mail, and so on. But it can be useful for starting programs with graphical user interfaces,<br />

too—such as a Web browser. In UNIX, you can do the following (provided that you have a browser at /usr/<br />

bin/firefox):<br />

os.system('/usr/bin/firefox')<br />

A Windows version would be (again use the path of a browser you have installed)<br />

os.system(r'c:\"Program Files"\"Mozilla Firefox"\firefox.exe')<br />

Note that I’ve been careful about enclosing Program Files and Mozilla Firefox in quotes; otherwise DOS<br />

(which handles the command) balks at the whitespace. (This may be important for directories in your PYTHONPATH<br />

as well.) Note also that you have to use backslashes here because DOS gets confused by forward slashes. If you run<br />

this, you will notice that the browser tries to open a Web site named Files"\Mozilla...—the part of the command<br />

after the whitespace. Also, if you try to run this from IDLE, a DOS window appears, but the browser doesn’t start until<br />

you close that DOS window. All in all, not exactly ideal behavior.<br />

Another function that suits the job better is the Windows-specific function os.startfile:<br />

os.startfile(r' c:\Program Files\Mozilla Firefox\firefox.exe')<br />

As you can see, os.startfile accepts a plain path, even if it contains whitespace. (That is, don’t enclose<br />

“Program Files” in quotes as in the os.system example.)<br />

Note that in Windows, your Python program keeps on running after the external program has been started by<br />

os.system (or os.startfile), whereas in UNIX, your Python program waits for the os.system command<br />

to finish.<br />

A BETTER SOLUTION: WEBBROWSER<br />

The os.system function is useful for a lot of things, but for the specific task of launching a Web browser<br />

there’s an even better solution: the webbrowser module. It contains a function called open that lets you automatically<br />

launch a Web browser to open the given URL. For example, if you want your program to open the<br />

Python Web site in a Web browser (either starting a new browser or using one that is already running), you<br />

simply use<br />

import webbrowser<br />

webbrowser.open('http://www.python.org')<br />

and the page should pop up. Pretty nifty, huh?

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!