我想要一个函数,给定一个导致name的NameError,它可以识别import可以解决它的包。
这部分很简单,我已经做过了,但是现在我有了一个额外的问题:我想在不引起副作用的情况下去做。下面是我现在使用的代码:
def necessaryImportFor(name):
from pkgutil import walk_packages
for package in walk_packages():
if package[1] == name:
return name
try:
if hasattr(__import__(package[1]), name):
return package[1]
except Exception as e:
print("Can't check " + package[1] + " on account of a " + e.__class__.__name__ + ": " + str(e))
print("No possible import satisfies " + name)问题是,这段代码实际上是__import__的每个模块。这意味着导入每个模块的每一个副作用都会发生。在测试我的代码时,我发现导入所有模块可能产生的副作用包括:
getpass请求密码input或raw_inputimport this)import antigravity)我考虑过的一个可能的解决方案是找到通往每个模块的路径(怎么做?在我看来,要做到这一点,唯一的方法是对模块进行import,然后使用来自inspect的一些方法对其进行解析,以找到每个class、def和=,它们本身并不在class或def中,但这似乎是一个巨大的皮塔,我不认为它适用于用C/C++而不是纯Python实现的模块。
另一种可能是启动一个子Python实例,该实例将其输出重定向到devnull,并在那里执行其检查,如果需要太长时间,则将其杀死。这将解决前四个子弹,第五个子弹是如此特殊的情况,我可以跳过antigravity。但是在这个函数中启动成千上万个Python实例似乎有点.笨重低效。
有没有人有更好的解决方案我还没想过?例如,是否有一种简单的方法可以让Python生成AST或其他东西而不实际导入模块?
发布于 2015-04-26 19:58:42
因此,我最终编写了一些方法,这些方法可以列出源文件中的所有内容,而无需导入源文件。
ast模块似乎没有特别好的文档,所以这有点像一个皮塔试图找出如何提取所有感兴趣的东西。不过,今天经过了6个小时的尝试和错误之后,我还是能够把它放在我的计算机上的3000+源文件上运行,而没有引发任何异常。
def listImportablesFromAST(ast_):
from ast import (Assign, ClassDef, FunctionDef, Import, ImportFrom, Name,
For, Tuple, TryExcept, TryFinally, With)
if isinstance(ast_, (ClassDef, FunctionDef)):
return [ast_.name]
elif isinstance(ast_, (Import, ImportFrom)):
return [name.asname if name.asname else name.name for name in ast_.names]
ret = []
if isinstance(ast_, Assign):
for target in ast_.targets:
if isinstance(target, Tuple):
ret.extend([elt.id for elt in target.elts])
elif isinstance(target, Name):
ret.append(target.id)
return ret
# These two attributes cover everything of interest from If, Module,
# and While. They also cover parts of For, TryExcept, TryFinally, and With.
if hasattr(ast_, 'body') and isinstance(ast_.body, list):
for innerAST in ast_.body:
ret.extend(listImportablesFromAST(innerAST))
if hasattr(ast_, 'orelse'):
for innerAST in ast_.orelse:
ret.extend(listImportablesFromAST(innerAST))
if isinstance(ast_, For):
target = ast_.target
if isinstance(target, Tuple):
ret.extend([elt.id for elt in target.elts])
else:
ret.append(target.id)
elif isinstance(ast_, TryExcept):
for innerAST in ast_.handlers:
ret.extend(listImportablesFromAST(innerAST))
elif isinstance(ast_, TryFinally):
for innerAST in ast_.finalbody:
ret.extend(listImportablesFromAST(innerAST))
elif isinstance(ast_, With):
if ast_.optional_vars:
ret.append(ast_.optional_vars.id)
return ret
def listImportablesFromSource(source, filename = '<Unknown>'):
from ast import parse
return listImportablesFromAST(parse(source, filename))
def listImportablesFromSourceFile(filename):
with open(filename) as f:
source = f.read()
return listImportablesFromSource(source, filename)上面的代码包含了一个标题问题:如何在不运行Python包的情况下检查它的内容?
但是,它给您留下了另一个问题:如何从Python包的名称中获得通向它的路径?
下面是我写的处理这个问题的文章:
class PathToSourceFileException(Exception):
pass
class PackageMissingChildException(PathToSourceFileException):
pass
class PackageMissingInitException(PathToSourceFileException):
pass
class NotASourceFileException(PathToSourceFileException):
pass
def pathToSourceFile(name):
'''
Given a name, returns the path to the source file, if possible.
Otherwise raises an ImportError or subclass of PathToSourceFileException.
'''
from os.path import dirname, isdir, isfile, join
if '.' in name:
parentSource = pathToSourceFile('.'.join(name.split('.')[:-1]))
path = join(dirname(parentSource), name.split('.')[-1])
if isdir(path):
path = join(path, '__init__.py')
if isfile(path):
return path
raise PackageMissingInitException()
path += '.py'
if isfile(path):
return path
raise PackageMissingChildException()
from imp import find_module, PKG_DIRECTORY, PY_SOURCE
f, path, (suffix, mode, type_) = find_module(name)
if f:
f.close()
if type_ == PY_SOURCE:
return path
elif type_ == PKG_DIRECTORY:
path = join(path, '__init__.py')
if isfile(path):
return path
raise PackageMissingInitException()
raise NotASourceFileException('Name ' + name + ' refers to the file at path ' + path + ' which is not that of a source file.')把这两段代码放在一起,我就有了这样的函数:
def listImportablesFromName(name, allowImport = False):
try:
return listImportablesFromSourceFile(pathToSourceFile(name))
except PathToSourceFileException:
if not allowImport:
raise
return dir(__import__(name))最后,下面是我在问题中提到的函数的实现:
def necessaryImportFor(name):
packageNames = []
def nameHandler(name):
packageNames.append(name)
from pkgutil import walk_packages
for package in walk_packages(onerror=nameHandler):
nameHandler(package[1])
# Suggestion: Sort package names by count of '.', so shallower packages are searched first.
for package in packageNames:
# Suggestion: just skip any package that starts with 'test.'
try:
if name in listImportablesForName(package):
return package
except ImportError:
pass
except PathToSourceFileException:
pass
return None我就是这么过周日的。
https://stackoverflow.com/questions/29049400
复制相似问题