Commits

Maciej Fijalkowski committed da030b8

a module finder

Comments (0)

Files changed (3)

+
+import os, sys
+
+class NotFound(Exception):
+    """ An exception raised when module was not found in sys.path
+    """
+
+def find_module(name, sys_path=sys.path):
+    """ Searches sys.path for possible parent paths for name (which is
+    a filesystem name). Returns a pair (entry in sys.path, name of module)
+    where name of module is a reasonable name to be passed as argument for
+    __import__
+    """
+    sys_path_dict = {}
+    for path in sys_path:
+        sys_path_dict[path] = None
+    bases = name.split(os.path.sep)
+    for i in range(len(bases) - 1, -1, -1):
+        prefix = os.path.sep.join(bases[:i])
+        if prefix in sys_path_dict:
+            modname = ".".join(bases[i:])
+            if modname.endswith('.pyc'):
+                modname = modname[:-4]
+            else:
+                assert modname.endswith(".py")
+                modname = modname[:-3]
+            return prefix, modname
+    raise NotFound
 
 def import_module(name):
-    """ Finds a module based on it's name.
+    """ Finds a module based on it's name. Looks for all paths above if they're
+    on sys.path. if so, loads the parent sys.path and then module. Might
+    not be 100% proof, but should work in most cases
+    """
+    sys_path_entry, modname = find_module(name)

test/test_base.py

 1956214 <code object <genexp>, file '/home/fijal/src/pypy-benchmarks/unladen_swallow/performance/bm_ai.py', line 46> #9 STORE_FAST
 """.split("\n")
 
-def test_parse_log_count():
-    parse_log_counts(LINES)
+#def test_parse_log_count():
+#    parse_log_counts(LINES)

test/test_module.py

+
+from module_finder import find_module
+
+def test_find_module():
+    sys_path = ["/usr/lib/python2.6", '/home/stuff']
+    path, modname = find_module('/usr/lib/python2.6/re.py', sys_path)
+    assert path == sys_path[0]
+    assert modname == 're'
+    path, modname = find_module('/usr/lib/python2.6/stuff/re.py', sys_path)
+    assert path == sys_path[0]
+    assert modname == 'stuff.re'
+    path, modname = find_module('/usr/lib/python2.6/stuff/re.pyc', sys_path)
+    assert path == sys_path[0]
+    assert modname == 'stuff.re'
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.