15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Earlier in this chapter, we described how the exec statement can be used with a file object argument to<br />

read the contents of a <strong>Python</strong> script and execute it. This can be accomplished with the following code<br />

segment:<br />

f = open(filename, 'r')<br />

exec f<br />

f.close()<br />

The three lines can be replaced by a single call to execfile():<br />

execfile(filename)<br />

Although the code above does execute a module, it does so only in its current execution environment (i.<br />

e., its global and local namespace). There may be a desire to execute a module with a different set of<br />

global and local namespaces instead of the default ones. The full syntax of execfile() is very similar to<br />

that of eval():<br />

execfile(filename, globals=globals(), locals=locals())<br />

Like eval(), both globals and locals are optional and default to the executing environments'<br />

namespaces if not given. If only globals is given, then locals defaults to globals. If provided, locals<br />

can be any mapping object [an object defining/overriding __getitem__()], although before 2.4, it was<br />

required to be a dictionary. Warning: be very careful with your local namespace (in terms of modifying<br />

it). It is much safer to pass in a dummy "locals" dictionary and check for any side effects. Altering the<br />

local namespace is not guaranteed by execfile()! See the <strong>Python</strong> Library Reference Manual's entry for<br />

execfile() for more details.<br />

14.4.3. Executing Modules as Scripts<br />

A new command-line option (or switch) was added in <strong>Python</strong> 2.4 that allows you to directly execute a<br />

module as a script from your shell or DOS prompt. When you are writing your own modules as scripts, it<br />

is easy to execute them. From your working directory, you would just call your script on the command<br />

line:<br />

$ myScript.py # or $ python myScript.py<br />

This is not as easy if you are dealing with modules that are part of the standard library, installed in sitepackages,<br />

or just modules in packages, especially if they also share the same name as an existing<br />

<strong>Python</strong> module. For example, let us say you wanted to run the free Web server that comes with <strong>Python</strong><br />

so that you can create and test Web pages and CGI scripts you wrote.<br />

You would have to type something like the following at the command line:

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

Saved successfully!

Ooh no, something went wrong!