是否可以以编程方式检测驻留在SVN中的python项目的依赖关系?
答案 0 :(得分:4)
这是一个增加一些精度的扭曲,如果你发现你经常检查杂项代码的依赖性,这可能会有用:
代码:
import __builtin__
import collections
import sys
IN_USE = collections.defaultdict(set)
_IMPORT = __builtin__.__import__
def _myimport(name, globs=None, locs=None, fromlist=None, level=-1):
global IN_USE
if fromlist is None:
fromlist = []
IN_USE[name].update(fromlist)
return _IMPORT(name, globs, locs, fromlist, level)
# monkey-patch __import__
setattr(__builtin__, '__import__', _myimport)
# import and run the target project here and run the routine
import foobar
foobar.do_something()
# when it finishes running, dump the imports
print 'modules and symbols imported by "foobar":'
for key in sorted(IN_USE.keys()):
print key
for name in sorted(IN_USE[key]):
print ' ', name
示例foobar
模块:
import byteplay
import cjson
def _other():
from os import path
from sys import modules
def do_something():
import hashlib
import lxml
_other()
输出:
modules and symbols imported by "foobar":
_hashlib
array
array
byteplay
cStringIO
StringIO
cjson
dis
findlabels
foobar
hashlib
itertools
lxml
opcode
*
__all__
operator
os
path
sys
modules
types
warnings
答案 1 :(得分:0)
绝对!如果您使用的是UNIX或Linux shell,grep
和awk
的简单组合将起作用;基本上,您要做的就是搜索包含“import
”关键字的行。
但是,如果您在任何环境中工作,您可以编写一个小的Python脚本来搜索您(不要忘记将字符串视为不可变序列,因此您可以执行类似{{1}的操作}。
一个棘手的地方,就是将那些if "import" in line: ...
ed模块与它们的包名相关联(第一个想到的是import
模块,在Ubuntu中它由{{1}提供。 }包)。
答案 2 :(得分:0)
Python代码可以使用运行时构造的字符串导入模块,因此唯一可靠的方法是运行代码。实际示例:当您使用SQLAlchemy的dbconnect
打开数据库时,库将根据数据库字符串的内容加载一个或多个db-api模块。
如果您愿意运行代码,可以通过在完成时检查sys.modules
来执行此操作,这是一种相对简单的方法:
>>> from sys import modules
>>> import codeofinterest
>>> execute_code_of_interest()
>>> print modules
[ long, list, of, loaded, modules ]
在这里,您应该记住,如果execute_code_of_interest()
修改sys.modules
,理论上这可能会失败,但我相信这在生产代码中非常罕见。