• No se han encontrado resultados

In interactive mode, Python displays the results of expressions. In script mode, however, Python doesn’t automatically display results.

In order to see output from a Python script, we’ll introduce theprintstatement and theprint()function. Theprintstatement is the Python 2.6 legacy construct.

Theprint() function is a new Python 3 construct that will replace the print statement. We’ll visit this

topic in depth inSeeing Output with the print() Function (or print Statement).

For now, you can use either one. We’ll show both. In the future, theprintstatement will be removed from the language.

4.3.1 The print Statement

Theprintstatement takes a list of values and prints their string representation on the standard output file. The standard output is typically directed to theTerminal window.

print "PI = ", 355.0/113.0

We can have the Python interpreter execute our script files. Application program scripts can be of any size or complexity. For the following examples, we’ll create a simple, two-line script, calledexample1.py.

example1.py

print 65, "F"

print ( 65 - 32 ) * 5 / 9, "C"

4.3.2 The

print()

function

Theprint() functions takes a list of values and prints their string representation on the standard output

file. The standard output is typically directed to theTerminal window.

Until Python 3, we have to request the print() function with a special introductory statement: ‘from __future__ import print_function’.

from __future__ import print_function print( "PI = ", 355.0/113.0 )

We can have the Python interpreter execute our script files. Application program scripts can be of any size or complexity. For the following examples, we’ll create a simple, two-line script, calledexample1.py.

example1.py

from __future__ import print_function print( 65, "F" )

print( ( 65 - 32 ) * 5 / 9, "C" )

4.3.3 Running a Script

There are several ways we can start the Python interpreter and have it evaluate our script file.

• Explicitly from the command line. In this case we’ll be running Python and providing the name of the script as an argument.

We’ll look at this in detail below.

• Implicitly from the command line. In this case, we’ll either use the GNU/Linux shell comment (sharp- bang marker) or we’ll depend on the file association in Windows.

This is slightly more complex, and we’ll look at this in detail below.

• Manually from withinIDLE . It’s important for newbies to remember thatIDLE shouldn’t be part of the final delivery of a working application. However, this is a great way to start development of an application program.

We won’t look at this in detail because it’s so easy. Hit F5. MacBook users may have to hit fnand F5.

Running Python scripts from the command-line applies to all operating systems. It is the core of delivering final applications. We may add an icon for launching the application, but under the hood, an application program is essentially a command-line start of the Python interpreter.

4.3.4 Explicit Command Line Execution

The simplest way to execute a script is to provide the script file name as a parameter to the python interpreter. In this style, we explicitly name both the interpreter and the input script. Here’s an example. python example1.py

This will provide theexample1.py file to the Python interpreter for execution.

4.3.5 Implicit Command-Line Execution

We can streamline the command that starts our application. For POSIX-standard operating systems (GNU/Linux, UNIX and MacOS), we make the script file itself executable and directing the shell to lo- cate the Python interpreter for us. For Windows users, we associate our script file with the python.exe interpreter. There are one or two steps to this.

1. Associate your file with the Python interpreter. Except for Windows, you make sure the first line is the following: ‘#!/usr/bin/env python’ . For Windows, you must assure that.pyfiles are associated withpython.exe and.pywfiles are associated withpythonw.exe.

The whole file will look like this:

#!/usr/bin/env python

print 65, "F"

print ( 65 - 32 ) * 5 / 9, "C"

2. For POSIX-standard operating systems, do achmod +x example1.pyto make the fileexample1.py executable. You only do this once, typically the first time you try to run the file. For Windows, you don’t need to do this.

Now you can run a script in most GNU/Linux environments by saying: ./example1.py

4.3.6 Windows Configuration

Windows users will need to be sure that python.exe is on their PATH. This is done with the System control panel. Click on theAdvancedtab. Click on theEnvironment Variables... button. Click on the System variablesPathline, and click theEdit... button. This will often have a long list of items, sometimes starting with ‘%SystemRoot%’. At the end of this list, add ‘";"’ and the direction location of Python.exe. On my machine, I put it inC:\Python26.

For Windows programmers, the windows command interpreter uses the last letters of the file name to associate a file with an interpreter. You can have Windows run the python.exe program whenever you double-click a .pyfile. This is done with theFolder Options control panel. TheFile Typestab allows you to pair a file type with a program that processes the file.

4.3.7 GNU/Linux Configuration

We have to be sure that the Python interpreter is in value of the PATH that our shell uses. We can’t delve into the details of each of the available UNIX Shells. However, the general rule is that the person who administers your POSIX computer should have installed Python and updated the /etc/profile to make Python available to all users. If, for some reason that didn’t get done, you can update your own.profile to add Python to yourPATHvariable.

The Sharp-Bang (“shebang”) Comment

The ‘#!’ technique depends on the way all of the POSIX shells handle scripting languages. When you enter a command that is the name of a file, the shell must first check the file for the “x” (execute) mode; this was the mode you added withchmod +x.

When execute mode is true, the shell must then check the first few bytes to see what kind of file it is. The first few bytes are termed themagic number; deep in the bowels of GNU/Linux there is a database that shows what the magic number means, and how to work with the various kinds of files. Some files are binary executables, and the operating system handles these directly.

When an executable file’s content begins with ‘#!’, it is a script files. The rest of the first line names the program that will interpret the script. In this case, we asked theenvprogram to find thepython interpreter. The shell finds the named program and runs it automatically, passing the name of script file as the last argument to the interpreter it found.

The very cool part of this trick is that ‘#!’ is acommentto Python. This first line is, in effect, directed at the shell, and ignored by Python. The shell glances at it to see what the language is, and Python studiously ignores it, since it was intended for the shell.

4.3.8 Another Script Example

Throughout the rest of this book, we’re going to use this script processing mode as the standard way to run Python programs. Many of the examples will be shown as though a file was sent to the interpreter.

For debugging and testing, it is sometimes useful to importthe program definitions, and do some manipu- lations interactively. We’ll touch on this inHacking Mode.

Here’s a second example. We’ll create a new file and write another small Python program. We’ll call it example2.py.

example2.py

#!/usr/bin/env python

"""Compute the odds of spinning red (or black) six times in a row on an American roulette wheel. """

print (18.0/38.0)**6

This is a one-line Python program with a two line module document string. That’s a good ratio to strive for.

After we finish editing, we mark this as executable using ‘chmod +x example2.py’. Since this is a property of the file, this is remains true no matter how many times we edit, copy or rename the file.

When we run this, we see the following.

$ ./example2.py 0.0112962280375

Which says that spinning six reds in a row is about a one in eighty-nine probability.