Clicking File Icons

If you’re not a fan of command lines, you can generally avoid them by launching Python scripts with file icon clicks, development GUIs, and other schemes that vary per platform. Let’s take a quick look at the first of these alternatives here.

Icon-Click Basics

Icon clicks are supported on most platforms in one form or another. Here’s a rundown of how these might be structured on your computer:

Windows icon clicks

On Windows, the Registry makes opening files with icon clicks easy. When installed, Python uses Windows filename associations to automatically register itself to be the program that opens Python program files when they are clicked. Because of that, it is possible to launch the Python programs you write by simply clicking (or double-clicking) on their file icons with your mouse cursor.

Specifically, a clicked file will be run by one of two Python programs, depending on its extension and the Python you’re running. In Pythons 3.2 and earlier, .py files are run by python.exe with a console (Command Prompt) window, and .pyw files are run by pythonw.exe files without a console. Byte code files are also run by these programs if clicked. Per Appendix B, in Python 3.3 and later (and where it’s installed separately), the new Window’s launchers’s py.exe and pyw.exe programs serve the same roles, opening .py and .pyw files, respectively.

Non-Windows icon clicks

On non-Windows systems, you will probably be able to perform a similar feat, but the icons, file explorer navigation schemes, and more may differ slightly. On Mac OS X, for instance, you might use PythonLauncher in the MacPython (or Python N.M) folder of your Applications folder to run by clicking in Finder.

On some Linux and other Unix systems, you may need to register the .py extension with your file explorer GUI, make your script executable using the #! line scheme of the preceding section, or associate the file MIME type with an application or command by editing files, installing programs, or using other tools. See your file explorer’s documentation for more details.

In other words, icon clicks generally work as you’d expect for your platform, but be sure to see the platform usage documentation “Python Setup and Usage” in Python’s standard manual set for more details as needed.

Clicking Icons on Windows

To illustrate, let’s keep using the script we wrote earlier, script1.py, repeated here to minimize page flipping:

# A first Python script
import sys                  # Load a library module
print(sys.platform)
print(2 ** 100)             # Raise 2 to a power
x = 'Spam!'
print(x * 8)                # String repetition

As we’ve seen, you can always run this file from a system command line:

C:\code> python script1.py
win32
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

However, icon clicks allow you to run the file without any typing at all. To do so, you have to find this file’s icon on your computer. On Windows 8, you might right-click the screen’s lower-left corner to open a File Explorer. On earlier Windows, you can select Computer (or My Computer in XP) in your Start button’s menu. There are additional ways to open a file explorer; once you do, work your way down on the C drive to your working directory.

At this point, you should have a file explorer window similar to that captured in Figure 3-1 (Windows 8 is being used here). Notice how the icons for Python files show up:

  • Source files have white backgrounds on Windows.

  • Byte code files show with black backgrounds.

Per the prior chapter, I created the byte code file in this figure by importing in Python 3.1; 3.2 and later instead store byte code files in the __pycache__ subdirectory also shown here, which I created by importing in 3.3 too. You will normally want to click (or otherwise run) the white source code files in order to pick up your most recent changes, not the byte code files—Python won’t check the source code file for changes if you launch byte code directly. To launch the file here, simply click on the icon for script1.py.

On Windows, Python program files show up as icons in file explorer windows and can automatically be run with a double-click of the mouse (though you might not see printed output or error messages this way).

Figure 3-1. On Windows, Python program files show up as icons in file explorer windows and can automatically be run with a double-click of the mouse (though you might not see printed output or error messages this way).

The input Trick on Windows

Unfortunately, on Windows, the result of clicking on a file icon may not be incredibly satisfying. In fact, as it is, this example script might generate a perplexing “flash” when clicked—not exactly the sort of feedback that budding Python programmers usually hope for! This is not a bug, but has to do with the way the Windows version of Python handles printed output.

By default, Python generates a pop-up black DOS console window (Command Prompt) to serve as a clicked file’s input and output. If a script just prints and exits, well, it just prints and exits—the console window appears, and text is printed there, but the console window closes and disappears on program exit. Unless you are very fast, or your machine is very slow, you won’t get to see your output at all. Although this is normal behavior, 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 around when you launch it with an icon click, simply put a call to the built-in input function at the very bottom of the script in 3.X (in 2.X use the name raw_input instead: see the note ahead). For example:

# A first Python script
import sys                  # Load a library module
print(sys.platform)
print(2 ** 100)             # Raise 2 to a power
x = 'Spam!'
print(x * 8)                # String repetition
input()                     # <== ADDED

In general, input reads and returns the next line of standard input, waiting if there is none yet available. The net effect in this context will be to pause the script, thereby keeping the output window shown in Figure 3-2 open until you press the Enter key.

When you click a program’s icon on Windows, you will be able to see its printed output if you include an input call at the very end of the script. But you only need to do so in this one context!

Figure 3-2. When you click a program’s icon on Windows, you will be able to see its printed output if you include an input call at the very end of the script. But you only need to do so in this one context!

Now that I’ve shown you this trick, keep in mind that it is usually only required for Windows, and then only if your script prints text and exits and only if you will launch the script by clicking its file icon. You should add this call to the bottom of your top-level files if and only if all of these three conditions apply. There is no reason to add this call in any other contexts, such as scripts you’ll run in command lines or the IDLE GUI (unless you’re unreasonably fond of pressing your computer’s Enter key!).[6] That may sound obvious, but it’s been another common mistake in live classes.

Before we move ahead, note that the input call applied here is the input counterpart of using the print function (and 2.X statement) for outputs. It is the simplest way to read user input, and it is more general than this example implies. For instance, input:

  • Optionally accepts a string that will be printed as a prompt (e.g., input('Press Enter to exit'))

  • Returns to your script a line of text read as a string (e.g., nextinput = input())

  • Supports input stream redirections at the system shell level (e.g., python spam.py < input.txt), just as the print statement does for output

We’ll use input in more advanced ways later in this text; for instance, Chapter 10 will apply it in an interactive loop. For now, it will help you see the output of simple scripts that you click to launch.

Note

Version skew note: If you are working in Python 2.X, use raw_input() instead of input() in this code. The former was renamed to the latter in Python 3.X. Technically, 2.X has an input function too, but it also evaluates strings as though they are program code typed into a script, and so will not work in this context (an empty string is an error). Python 3.X’s input (and 2.X’s raw_input) simply returns the entered text as a character string, unevaluated. To simulate 2.X’s input in 3.X, use eval(input()).

Be aware, though, that because this runs the entered text as though it were program code, this may have security implications that we’ll largely ignore here, except to say that you should trust the source of the entered text; if you don’t, stick to just plain input in 3.X and raw_input in 2.X.

Other Icon-Click Limitations

Even with the prior section’s input trick, clicking file icons is not without its perils. You also may not get to see Python error messages. If your script generates an error, the error message text is written to the pop-up console window—which then immediately disappears! Worse, adding an input call to your file will not help this time because your script will likely abort long before it reaches this call. In other words, you won’t be able to tell what went wrong.

When we discuss exceptions later in this book, you’ll learn that it is possible to write code to intercept, process, and recover from errors so that they do not terminate your programs. Watch for the discussion of the try statement later in this book for an alternative way to keep the console window from closing on errors. We’ll also learn how to redirect printed text to files for later inspection when we study print operations. Barring such support in your code, though, errors and prints disappear for clicked programs.

Because of these limitations, it is probably best to view icon clicks as a way to launch programs after they have been debugged, or have been instrumented to write their output to a file and catch and process any important errors. Especially when you’re starting out, I recommend using other techniques—such as system command lines and IDLE (discussed further in the section The IDLE User Interface)—so that you can see generated error messages and view your normal output without resorting to extra coding.



[6] Conversely, it is also possible to completely suppress the pop-up console window (a.k.a. Command Prompt) for clicked files on Windows when you don’t want to see printed text. Files whose names end in a .pyw extension will display only windows constructed by your script, not the default console window. .pyw files are simply .py source files that have this special operational behavior on Windows. They are mostly used for Python-coded user interfaces that build windows of their own, often in conjunction with various techniques for saving printed output and errors to files. As implied earlier, Python achieves this when it is installed by associating a special executable (pythonw.exe in 3.2 and earlier and pyw.exe as of 3.3) to open .pyw files when clicked.