python - 列出 Python 文件中使用的所有第三方包及其自身的函数

标签 python

我有很多 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 解析您的文件模块并检查所有 ImportImportFrom 语句。

给你一个想法,这里有一个例子:

>>> 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'

您的脚本可以像这样工作:

  1. 通过ast.parse解析源文件
  2. 使用 ast.walk() 访问每个节点
  3. 如果节点是 ImportImportFrom 对象,则检查名称并执行您必须执行的操作。

使用 ast 比正则表达式或自定义解析器更容易、更健壮。

关于python - 列出 Python 文件中使用的所有第三方包及其自身的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34899733/

相关文章:

python - Django 按计算字段对记录进行排序

python - Keras 密集输出层形状错误

python - 处理在 python、tornado 和 redis 上运行的网站中的外来字符

python - 为什么 Dash-Plotly 应用程序中的 map 尺寸太小?

python - 为什么 Python 代码在函数中运行得更快?

python - 我在 Databricks 文件存储中使用命令 'dbutils.fs.rm' 删除了一个文件。有办法找回来吗?

Supervisord 的 Python 导入错误

Python 的 sum() 会将字符串列表加在一起。有什么用?

python - 如何在 Jupyter Notebook 中制作包含可点击单元格的表格?

python - Pygame 组更新不带参数