On 08/04/2011 07:43 AM, Billy Mays wrote:
Hey c.l.p.,

I wrote a little python script that finds the file that a python module
came from.  Does anyone see anything wrong with this script?

#!/usr/bin/python

import sys
if __name__ == '__main__':
      if len(sys.argv)>  1:
          try:
              m = __import__(sys.argv[1])
              sys.stdout.write(m.__file__ + '\n')

For a quick script in a controlled environment, not bad. In a hostile environment, I'd be nervous about running arbitrary module code triggered by the import. Even if non-malicious, some imports (like PyCrypto) may have some initialization lag which would be nice to avoid. I think I'd make use of imp.find_module to write it something like this (untested)

  from sys import argv, stderr
  import imp
  type_map = {
    imp.PY_SOURCE: "Source file",
    imp.PY_COMPILED: "Compiled code object",
    imp.C_EXTENSION: "Dynamically loadabld shared library",
    imp.PKG_DIRECTORY: "Package directory",
    imp.C_BUILTIN: "Built-in",
    imp.PY_FROZEN: "Frozen module",
    }
  if __name__ == '__main__':
    if len(argv) > 1:
      for modname in argv[1:]:
        try:
          fp, pth, desc = imp.find_module(modname)
          (suffix, mode, type_) = desc
          if fp is not None: fp.close()
          print("%s\t[%s]" % (
            pth,
            type_map.get(type_, "UNKNOWN")
            ))
        except ImportError:
          stderr.write("No such module '%s'\n" % modname)
    else:
      stderr.write("Usage: pywhich <module> [<module>...]\n")

I don't know a good way to tap into other import hooks (such as the zipfile import) to augment that type_map dictionary.

-tkc



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to