title: Return a list of imported Python modules used in a script?
body: <p>I am writing a program that categorizes a list of Python files by which modules they import. As such I need to scan the collection of .py files ad return a list of which modules they import. As an example, if one of the files I import has the following lines:</p>
  
  <pre><code>import os
  import sys, gtk
  </code></pre>
  
  <p>I would like it to return:</p>
  
  <pre><code>["os", "sys", "gtk"]
  </code></pre>
  
  <p>I played with modulefinder and wrote:</p>
  
  <pre><code>from modulefinder import ModuleFinder
  
  finder = ModuleFinder()
  finder.run_script('testscript.py')
  
  print 'Loaded modules:'
  for name, mod in finder.modules.iteritems():
      print '%s ' % name,
  </code></pre>
  
  <p>but this returns more than just the modules used in the script. As an example in a script which merely has:</p>
  
  <pre><code>import os
  print os.getenv('USERNAME')
  </code></pre>
  
  <p>The modules returned from the ModuleFinder script return:</p>
  
  <pre><code>tokenize  heapq  __future__  copy_reg  sre_compile  _collections  cStringIO  _sre  functools  random  cPickle  __builtin__  subprocess  cmd  gc  __main__  operator  array  select  _heapq  _threading_local  abc  _bisect  posixpath  _random  os2emxpath  tempfile  errno  pprint  binascii  token  sre_constants  re  _abcoll  collections  ntpath  threading  opcode  _struct  _warnings  math  shlex  fcntl  genericpath  stat  string  warnings  UserDict  inspect  repr  struct  sys  pwd  imp  getopt  readline  copy  bdb  types  strop  _functools  keyword  thread  StringIO  bisect  pickle  signal  traceback  difflib  marshal  linecache  itertools  dummy_thread  posix  doctest  unittest  time  sre_parse  os  pdb  dis
  </code></pre>
  
  <p>...whereas I just want it to return 'os', as that was the module used in the script.</p>
  
  <p>Can anyone help me achieve this?</p>
  
  <p><strong>UPDATE</strong>: I just want to clarify that I would like to do this without running the Python file being analyzed, and just scanning the code.</p>