返回脚本中使用的导入Python模块的列表?

2024-05-19 20:54:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,它对Python文件列表进行分类,根据这些文件导入模块。因此,我需要扫描.py文件的集合,并返回它们导入的模块的列表。例如,如果我导入的某个文件具有以下行:

import os
import sys, gtk

我想要它回来:

["os", "sys", "gtk"]

我和modulefinder一起玩,写下:

from modulefinder import ModuleFinder

finder = ModuleFinder()
finder.run_script('testscript.py')

print 'Loaded modules:'
for name, mod in finder.modules.iteritems():
    print '%s ' % name,

但这不仅仅返回脚本中使用的模块。作为脚本中的一个例子,它仅仅具有:

import os
print os.getenv('USERNAME')

从ModuleFinder脚本返回的模块返回:

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

…而我只希望它返回'os',因为这是脚本中使用的模块。

有谁能帮我实现这个目标吗?

更新:我只想澄清一下,我希望在不运行正在分析的Python文件,只扫描代码的情况下执行此操作。


Tags: 模块文件pyimport脚本modulesgtk列表
3条回答

这取决于你想要多彻底。使用的模块是一个图灵完整的问题:一些python代码使用惰性导入只导入它们在特定运行中实际使用的东西,一些代码生成动态导入的东西(例如插件系统)。

python-v将跟踪import语句——这可以说是最简单的检查。

最好的方法是使用http://furius.ca/snakefood/包。作者已经完成了所有必需的工作,不仅获得了直接导入的模块,而且还使用AST来解析运行时依赖关系的代码,这将是一个更为静态的分析所忽略的。

制作了一个命令示例来演示:

sfood ./example.py | sfood-cluster > example.deps

它将生成每个唯一模块的基本依赖文件。更详细的使用:

sfood -r -i ./example.py | sfood-cluster > example.deps

要遍历树并查找所有导入,也可以在代码中执行此操作: 请注意-此例程的AST块是从具有此版权的snakefood源中提取的:版权所有(C)2001-2007 Martin Blais。保留所有权利。

 import os
 import compiler
 from compiler.ast import Discard, Const
 from compiler.visitor import ASTVisitor

 def pyfiles(startPath):
     r = []
     d = os.path.abspath(startPath)
     if os.path.exists(d) and os.path.isdir(d):
         for root, dirs, files in os.walk(d):
             for f in files:
                 n, ext = os.path.splitext(f)
                 if ext == '.py':
                     r.append([d, f])
     return r

 class ImportVisitor(object):
     def __init__(self):
         self.modules = []
         self.recent = []
     def visitImport(self, node):
         self.accept_imports()
         self.recent.extend((x[0], None, x[1] or x[0], node.lineno, 0)
                            for x in node.names)
     def visitFrom(self, node):
         self.accept_imports()
         modname = node.modname
         if modname == '__future__':
             return # Ignore these.
         for name, as_ in node.names:
             if name == '*':
                 # We really don't know...
                 mod = (modname, None, None, node.lineno, node.level)
             else:
                 mod = (modname, name, as_ or name, node.lineno, node.level)
             self.recent.append(mod)
     def default(self, node):
         pragma = None
         if self.recent:
             if isinstance(node, Discard):
                 children = node.getChildren()
                 if len(children) == 1 and isinstance(children[0], Const):
                     const_node = children[0]
                     pragma = const_node.value
         self.accept_imports(pragma)
     def accept_imports(self, pragma=None):
         self.modules.extend((m, r, l, n, lvl, pragma)
                             for (m, r, l, n, lvl) in self.recent)
         self.recent = []
     def finalize(self):
         self.accept_imports()
         return self.modules

 class ImportWalker(ASTVisitor):
     def __init__(self, visitor):
         ASTVisitor.__init__(self)
         self._visitor = visitor
     def default(self, node, *args):
         self._visitor.default(node)
         ASTVisitor.default(self, node, *args) 

 def parse_python_source(fn):
     contents = open(fn, 'rU').read()
     ast = compiler.parse(contents)
     vis = ImportVisitor() 

     compiler.walk(ast, vis, ImportWalker(vis))
     return vis.finalize()

 for d, f in pyfiles('/Users/bear/temp/foobar'):
     print d, f
     print parse_python_source(os.path.join(d, f)) 

您可能想尝试dis(双关语):

import dis
from collections import defaultdict
from pprint import pprint

statements = """
from __future__ import (absolute_import,
                        division)
import os
import collections, itertools
from math import *
from gzip import open as gzip_open
from subprocess import check_output, Popen
"""

instructions = dis.get_instructions(statements)
imports = [__ for __ in instructions if 'IMPORT' in __.opname]

grouped = defaultdict(list)
for instr in imports:
    grouped[instr.opname].append(instr.argval)

pprint(grouped)

产出

defaultdict(<class 'list'>,
            {'IMPORT_FROM': ['absolute_import',
                             'division',
                             'open',
                             'check_output',
                             'Popen'],
             'IMPORT_NAME': ['__future__',
                             'os',
                             'collections',
                             'itertools',
                             'math',
                             'gzip',
                             'subprocess'],
             'IMPORT_STAR': [None]})

导入的模块是grouped['IMPORT_NAME']

相关问题 更多 >