Back to index

python3.2  3.2.2
Classes | Functions | Variables
runpy Namespace Reference

Classes

class  _TempModule
class  _ModifiedArgv0

Functions

def _run_code
def _run_module_code
def _get_filename
def _get_module_details
def _run_module_as_main
def run_module
def _get_main_module_details
def _get_importer
def _get_code_from_file
def run_path

Variables

list __all__

Detailed Description

runpy.py - locating and running Python code using the module namespace

Provides support for locating and running Python scripts using the Python
module namespace instead of the native filesystem.

This allows Python code to play nicely with non-filesystem based PEP 302
importers when locating support scripts as well as when importing modules.

Function Documentation

def runpy._get_code_from_file (   fname) [private]

Definition at line 223 of file runpy.py.

00223 
00224 def _get_code_from_file(fname):
00225     # Check for a compiled file first
00226     with open(fname, "rb") as f:
00227         code = read_code(f)
00228     if code is None:
00229         # That didn't work, so try it as normal source code
00230         with open(fname, "rb") as f:
00231             code = compile(f.read(), fname, 'exec')
00232     return code

Here is the call graph for this function:

Here is the caller graph for this function:

def runpy._get_filename (   loader,
  mod_name 
) [private]

Definition at line 93 of file runpy.py.

00093 
00094 def _get_filename(loader, mod_name):
00095     for attr in ("get_filename", "_get_filename"):
00096         meth = getattr(loader, attr, None)
00097         if meth is not None:
00098             return meth(mod_name)
00099     return None
00100 
# Helper to get the loader, code and filename for a module

Here is the call graph for this function:

Here is the caller graph for this function:

def runpy._get_importer (   path_name) [private]
Python version of PyImport_GetImporter C API function

Definition at line 195 of file runpy.py.

00195 
00196 def _get_importer(path_name):
00197     """Python version of PyImport_GetImporter C API function"""
00198     cache = sys.path_importer_cache
00199     try:
00200         importer = cache[path_name]
00201     except KeyError:
00202         # Not yet cached. Flag as using the
00203         # standard machinery until we finish
00204         # checking the hooks
00205         cache[path_name] = None
00206         for hook in sys.path_hooks:
00207             try:
00208                 importer = hook(path_name)
00209                 break
00210             except ImportError:
00211                 pass
00212         else:
00213             # The following check looks a bit odd. The trick is that
00214             # NullImporter throws ImportError if the supplied path is a
00215             # *valid* directory entry (and hence able to be handled
00216             # by the standard import machinery)
00217             try:
00218                 importer = imp.NullImporter(path_name)
00219             except ImportError:
00220                 return None
00221         cache[path_name] = importer
00222     return importer

Here is the caller graph for this function:

def runpy._get_main_module_details ( ) [private]

Definition at line 180 of file runpy.py.

00180 
00181 def _get_main_module_details():
00182     # Helper that gives a nicer error message when attempting to
00183     # execute a zipfile or directory by invoking __main__.py
00184     main_name = "__main__"
00185     try:
00186         return _get_module_details(main_name)
00187     except ImportError as exc:
00188         if main_name in str(exc):
00189             raise ImportError("can't find %r module in %r" %
00190                               (main_name, sys.path[0]))
00191         raise
00192 
00193 
00194 # XXX (ncoghlan): Perhaps expose the C API function
# as imp.get_importer instead of reimplementing it in Python?

Here is the call graph for this function:

Here is the caller graph for this function:

def runpy._get_module_details (   mod_name) [private]

Definition at line 101 of file runpy.py.

00101 
00102 def _get_module_details(mod_name):
00103     loader = get_loader(mod_name)
00104     if loader is None:
00105         raise ImportError("No module named %s" % mod_name)
00106     if loader.is_package(mod_name):
00107         if mod_name == "__main__" or mod_name.endswith(".__main__"):
00108             raise ImportError("Cannot use package as __main__ module")
00109         try:
00110             pkg_main_name = mod_name + ".__main__"
00111             return _get_module_details(pkg_main_name)
00112         except ImportError as e:
00113             raise ImportError(("%s; %r is a package and cannot " +
00114                                "be directly executed") %(e, mod_name))
00115     code = loader.get_code(mod_name)
00116     if code is None:
00117         raise ImportError("No code object available for %s" % mod_name)
00118     filename = _get_filename(loader, mod_name)
00119     return mod_name, loader, code, filename
00120 
00121 # XXX ncoghlan: Should this be documented and made public?
00122 # (Current thoughts: don't repeat the mistake that lead to its
00123 # creation when run_module() no longer met the needs of
# mainmodule.c, but couldn't be changed because it was public)

Here is the call graph for this function:

Here is the caller graph for this function:

def runpy._run_code (   code,
  run_globals,
  init_globals = None,
  mod_name = None,
  mod_fname = None,
  mod_loader = None,
  pkg_name = None 
) [private]
Helper to run code in nominated namespace

Definition at line 64 of file runpy.py.

00064 
00065               mod_loader=None, pkg_name=None):
00066     """Helper to run code in nominated namespace"""
00067     if init_globals is not None:
00068         run_globals.update(init_globals)
00069     run_globals.update(__name__ = mod_name,
00070                        __file__ = mod_fname,
00071                        __cached__ = None,
00072                        __loader__ = mod_loader,
00073                        __package__ = pkg_name)
00074     exec(code, run_globals)
00075     return run_globals

Here is the call graph for this function:

Here is the caller graph for this function:

def runpy._run_module_as_main (   mod_name,
  alter_argv = True 
) [private]
Runs the designated module in the __main__ namespace

   Note that the executed module will have full access to the
   __main__ namespace. If this is not desirable, the run_module()
   function should be used to run the module code in a fresh namespace.

   At the very least, these variables in __main__ will be overwritten:
       __name__
       __file__
       __cached__
       __loader__
       __package__

Definition at line 124 of file runpy.py.

00124 
00125 def _run_module_as_main(mod_name, alter_argv=True):
00126     """Runs the designated module in the __main__ namespace
00127 
00128        Note that the executed module will have full access to the
00129        __main__ namespace. If this is not desirable, the run_module()
00130        function should be used to run the module code in a fresh namespace.
00131 
00132        At the very least, these variables in __main__ will be overwritten:
00133            __name__
00134            __file__
00135            __cached__
00136            __loader__
00137            __package__
00138     """
00139     try:
00140         if alter_argv or mod_name != "__main__": # i.e. -m switch
00141             mod_name, loader, code, fname = _get_module_details(mod_name)
00142         else:          # i.e. directory or zipfile execution
00143             mod_name, loader, code, fname = _get_main_module_details()
00144     except ImportError as exc:
00145         # Try to provide a good error message
00146         # for directories, zip files and the -m switch
00147         if alter_argv:
00148             # For -m switch, just display the exception
00149             info = str(exc)
00150         else:
00151             # For directories/zipfiles, let the user
00152             # know what the code was looking for
00153             info = "can't find '__main__' module in %r" % sys.argv[0]
00154         msg = "%s: %s" % (sys.executable, info)
00155         sys.exit(msg)
00156     pkg_name = mod_name.rpartition('.')[0]
00157     main_globals = sys.modules["__main__"].__dict__
00158     if alter_argv:
00159         sys.argv[0] = fname
00160     return _run_code(code, main_globals, None,
00161                      "__main__", fname, loader, pkg_name)

Here is the call graph for this function:

Here is the caller graph for this function:

def runpy._run_module_code (   code,
  init_globals = None,
  mod_name = None,
  mod_fname = None,
  mod_loader = None,
  pkg_name = None 
) [private]
Helper to run code in new namespace with sys modified

Definition at line 78 of file runpy.py.

00078 
00079                     mod_loader=None, pkg_name=None):
00080     """Helper to run code in new namespace with sys modified"""
00081     with _TempModule(mod_name) as temp_module, _ModifiedArgv0(mod_fname):
00082         mod_globals = temp_module.module.__dict__
00083         _run_code(code, mod_globals, init_globals,
00084                   mod_name, mod_fname, mod_loader, pkg_name)
00085     # Copy the globals of the temporary module, as they
00086     # may be cleared when the temporary module goes away
00087     return mod_globals.copy()
00088 
00089 
00090 # This helper is needed due to a missing component in the PEP 302
00091 # loader protocol (specifically, "get_filename" is non-standard)
00092 # Since we can't introduce new features in maintenance releases,
# support was added to zipimporter under the name '_get_filename'

Here is the call graph for this function:

Here is the caller graph for this function:

def runpy.run_module (   mod_name,
  init_globals = None,
  run_name = None,
  alter_sys = False 
)
Execute a module's code without importing it

   Returns the resulting top level namespace dictionary

Definition at line 163 of file runpy.py.

00163 
00164                run_name=None, alter_sys=False):
00165     """Execute a module's code without importing it
00166 
00167        Returns the resulting top level namespace dictionary
00168     """
00169     mod_name, loader, code, fname = _get_module_details(mod_name)
00170     if run_name is None:
00171         run_name = mod_name
00172     pkg_name = mod_name.rpartition('.')[0]
00173     if alter_sys:
00174         return _run_module_code(code, init_globals, run_name,
00175                                 fname, loader, pkg_name)
00176     else:
00177         # Leave the sys module alone
00178         return _run_code(code, {}, init_globals, run_name,
00179                          fname, loader, pkg_name)

Here is the call graph for this function:

Here is the caller graph for this function:

def runpy.run_path (   path_name,
  init_globals = None,
  run_name = None 
)
Execute code located at the specified filesystem location

   Returns the resulting top level namespace dictionary

   The file path may refer directly to a Python script (i.e.
   one that could be directly executed with execfile) or else
   it may refer to a zipfile or directory containing a top
   level __main__.py script.

Definition at line 233 of file runpy.py.

00233 
00234 def run_path(path_name, init_globals=None, run_name=None):
00235     """Execute code located at the specified filesystem location
00236 
00237        Returns the resulting top level namespace dictionary
00238 
00239        The file path may refer directly to a Python script (i.e.
00240        one that could be directly executed with execfile) or else
00241        it may refer to a zipfile or directory containing a top
00242        level __main__.py script.
00243     """
00244     if run_name is None:
00245         run_name = "<run_path>"
00246     importer = _get_importer(path_name)
00247     if isinstance(importer, imp.NullImporter):
00248         # Not a valid sys.path entry, so run the code directly
00249         # execfile() doesn't help as we want to allow compiled files
00250         code = _get_code_from_file(path_name)
00251         return _run_module_code(code, init_globals, run_name, path_name)
00252     else:
00253         # Importer is defined for path, so add it to
00254         # the start of sys.path
00255         sys.path.insert(0, path_name)
00256         try:
00257             # Here's where things are a little different from the run_module
00258             # case. There, we only had to replace the module in sys while the
00259             # code was running and doing so was somewhat optional. Here, we
00260             # have no choice and we have to remove it even while we read the
00261             # code. If we don't do this, a __loader__ attribute in the
00262             # existing __main__ module may prevent location of the new module.
00263             main_name = "__main__"
00264             saved_main = sys.modules[main_name]
00265             del sys.modules[main_name]
00266             try:
00267                 mod_name, loader, code, fname = _get_main_module_details()
00268             finally:
00269                 sys.modules[main_name] = saved_main
00270             pkg_name = ""
00271             with _TempModule(run_name) as temp_module, \
00272                  _ModifiedArgv0(path_name):
00273                 mod_globals = temp_module.module.__dict__
00274                 return _run_code(code, mod_globals, init_globals,
00275                                     run_name, fname, loader, pkg_name).copy()
00276         finally:
00277             try:
00278                 sys.path.remove(path_name)
00279             except ValueError:
00280                 pass
00281 

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 [
00002     "run_module", "run_path",
00003 ]

Definition at line 20 of file runpy.py.