我有很多 python 包,都是我的同事写的,我想写一个工具来检查他们依赖哪些第三方包。
像这样
#it is my package, need to check,call it example.py
#We have more than one way to import a package, It is a problem need to consider too
from third_party_packages import third_party_function
def my_function(arg):
return third_party_function(arg)
并且该工具应该像这样工作
result = tool(example.py)
#this result should be a dict like this structure
#{"third_party_function":["my_function",]}
#Means "my_function" relies on "third_party_function"
我不知道该怎么做,我能想出的实现这个工具的方法是一行一行地读取 Python 文件作为字符串,然后使用正则表达式对其进行比较。 你能给我一些建议吗?
如果你不明白我的意思,请评论 你的问题,我会尽快解决。 谢谢!
最佳答案
您可以使用 ast
解析您的文件模块并检查所有 Import
和 ImportFrom
语句。
给你一个想法,这里有一个例子:
>>> import ast
>>> tree = ast.parse('import a; from b import c')
>>> tree.body
[<_ast.Import object at 0x7f3041263860>, <_ast.ImportFrom object at 0x7f3041262c18>]
>>> tree.body[0].names[0].name
'a'
>>> tree.body[1].module
'b'
>>> tree.body[1].names[0].name
'c'
您的脚本可以像这样工作:
- 通过
ast.parse
解析源文件 - 使用
ast.walk()
访问每个节点 - 如果节点是
Import
或ImportFrom
对象,则检查名称并执行您必须执行的操作。
使用 ast
比正则表达式或自定义解析器更容易、更健壮。
关于python - 列出 Python 文件中使用的所有第三方包及其自身的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34899733/