12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The raw_input TrickUnfortunately, on Windows, the result of clicking on a file icon may not be incrediblysatisfying. In fact, as it is, this example script generates a perplexing “flash” whenclicked—not the sort of feedback that budding <strong>Python</strong> programmers usually hopefor! This is not a bug, but it has to do with the way the Windows port handlesprinted output.By default, <strong>Python</strong> generates a pop-up black DOS console window to serve as aclicked file’s input and output. If a script prints and exits, then, well, it just printsand exits—the console window appears, and text is printed there, but the consolewindow closes and disappears on program exit. Unless you are very fast, or yourmachine is very slow, you won’t get to see your output at all. Although this is normalbehavior, it’s probably not what you had in mind.Luckily, it’s easy to work around this. If you need your script’s output to stick aroundwhen you launch it with an icon click, simply put a call to the built-in raw_input functionat the very bottom of the script. For example:# A commentimport sysprint sys.platformprint 2 ** 100raw_input( )# ADDEDIn general, raw_input reads the next line of standard input, waiting if there is noneyet available. The net effect in this context will be to pause the script, thereby keepingthe output window shown in Figure 3-2 open until you press the Enter key.Figure 3-2. When you click a program’s icon on Windows, you will be able to see its printed outputif you add a raw_input() call to the very end of the script. But you only need to do so in thiscontext!Now that I’ve shown you this trick, keep in mind that it is usually only required forWindows, and then only if your script prints text and exits, and only if you willlaunch the script by clicking its file icon. You should add this call to the bottom of44 | Chapter 3: How You Run Programs

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

Saved successfully!

Ooh no, something went wrong!