Using exec to Run Module Files

In fact, there are more ways to run code stored in module files than have yet been exposed here. For instance, the exec(open('module.py').read()) built-in function call is another way to launch files from the interactive prompt without having to import and later reload. Each exec runs the current version of the file, without requiring later reloads (script1.py is as we left it after a reload in the prior section):

C:\misc> c:\python30\python
>>> exec(open('script1.py').read())
win32
65536
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

...change script1.py in a text edit window...

>>> exec(open('script1.py').read())
win32
4294967296
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

The exec call has an effect similar to an import, but it doesn’t technically import the module—by default, each time you call exec this way it runs the file anew, as though you had pasted it in at the place where exec is called. Because of that, exec does not require module reloads after file changes—it skips the normal module import logic.

On the downside, because it works as if pasting code into the place where it is called, exec, like the from statement mentioned earlier, has the potential to silently overwrite variables you may currently be using. For example, our script1.py assigns to a variable named x. If that name is also being used in the place where exec is called, the name’s value is replaced:

>>> x = 999
>>> exec(open('script1.py').read())     # Code run in this namespace by default
...same outout...
>>> x                                   # Its assignments can overwrite names here
'Spam!'

By contrast, the basic import statement runs the file only once per process, and it makes the file a separate module namespace so that its assignments will not change variables in your scope. The price you pay for the namespace partitioning of modules is the need to reload after changes.


Note

Version skew note: Python 2.6 also includes an execfile('module.py') built-in function, in addition to allowing the form exec(open('module.py')), which both automatically read the file’s content. Both of these are equivalent to the exec(open('module.py').read()) form, which is more complex but runs in both 2.6 and 3.0.

Unfortunately, neither of these two simpler 2.6 forms is available in 3.0, which means you must understand both files and their read methods to fully understand this technique today (alas, this seems to be a case of aesthetics trouncing practicality in 3.0). In fact, the exec form in 3.0 involves so much typing that the best advice may simply be not to do it—it’s usually best to launch files by typing system shell command lines or by using the IDLE menu options described in the next section. For more on the file interfaces used by the 3.0 exec form, see Chapter 9.