Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

The exec Statement

The import statement, in effect, executes the module file. Typically, the files we import are defined as sequences of definitions. Since our main program often begins with a series of import statements, these modules are imported into the global namespace. Python also optimizes the modules brought in by the import statement so that they are only imported once.

The exec statement can execute a file, a string of Python code, as well as a code created by the compile function. Unlike the import statement, it doesn't optimize module definitions or create and save a new namespace.

exec expression

The functions eval and execfile do essentially the same thing.

Fundamental Assumptions

The exec statement, eval function and execfile functions are dangerous tools. These break one of the Fundamental Assumptions: the source you are reading is the source that is being executed. A program that uses the exec statement or eval function is incorprating other source statements into the program dynamically. This can be hard to follow, maintain or enhance.

Generally, the exec statement is something that must be used with some care. The most common use is to bring in a set of configuration parameters written as simple Python assignment statements. For example, we might use a file like the following as the configuration paramaters for a program.

db_server= "dbs_prod_01"
db_port= "3306"
db_name= "PROD"

 
 
  Published under the terms of the Open Publication License Design by Interspire