-
Notifications
You must be signed in to change notification settings - Fork 201
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
cache source on import of modules that may contain kernels. Closes #416
1 parent
d51b27e
commit 84f4725
Showing
4 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import sys | ||
import builtins | ||
import linecache | ||
import tokenize | ||
import logging | ||
import importlib.machinery as im | ||
|
||
from artiq.experiment import kernel, portable | ||
|
||
|
||
__all__ = ["install_hook"] | ||
|
||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
cache = dict() | ||
im_exec_module = None | ||
linecache_getlines = None | ||
|
||
|
||
def hook_exec_module(self, module): | ||
im_exec_module(self, module) | ||
if (hasattr(module, "__file__") | ||
# Heuristic to determine if the module may contain ARTIQ kernels. | ||
# This breaks if kernel is not imported the usual way. | ||
and ((getattr(module, "kernel", None) is kernel) | ||
or (getattr(module, "portable", None) is portable))): | ||
fn = module.__file__ | ||
try: | ||
with tokenize.open(fn) as fp: | ||
cache[fn] = fp.readlines() | ||
except: | ||
logger.warning("failed to add '%s' to cache", fn, exc_info=True) | ||
else: | ||
logger.debug("added '%s' to cache", fn) | ||
|
||
|
||
def hook_getlines(filename, module_globals=None): | ||
if filename in cache: | ||
return cache[filename] | ||
else: | ||
return linecache_getlines(filename, module_globals) | ||
|
||
|
||
def install_hook(): | ||
global im_exec_module, linecache_getlines | ||
|
||
im_exec_module = im.SourceFileLoader.exec_module | ||
im.SourceFileLoader.exec_module = hook_exec_module | ||
|
||
linecache_getlines = linecache.getlines | ||
linecache.getlines = hook_getlines | ||
|
||
logger.debug("hook installed") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters