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

列出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 m

我有很多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文件作为字符串,并使用正则表达式进行比较。 你能给我一些建议吗

如果你不知道我的意思,请评论 你的问题,我会尽快解决。
谢谢

您可以使用模块解析文件,并检查所有
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 >>>tree=ast.parse('导入a;从b导入c') >>>树体 [, ] >>>tree.body[0]。名称[0]。名称 “a” >>>tree.body[1].模块 “b” >>>tree.body[1]。名称[0]。名称 “c” 您的脚本可以这样工作:

  • 通过解析源文件
  • 使用
  • 如果节点是
    Import
    ImportFrom
    对象,则检查名称并执行必须执行的操作

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

    如果您有一个工作环境,即python安装中安装的所有包,您可以使用
    pip
    pip freeze>requirements.pip
    来创建文件
    requirements.pip
    列出所有包安装(间接地说,软件包需要运行您的项目)这不是一个容易回答的问题。感谢您的建议,不幸的是,并非所有的软件包都是由pip安装的,有些软件包是我们自己编写的。我需要处理它们。使用逐行搜索可能是最好的,我能想到的替代方法是运行每个脚本,然后检查导入到名称空间的内容。但无论如何,这可能会更加笨拙和不可靠。您可以使用一些递归和反射来实现这一点。使用_uimport _;()动态导入Python文件,我认为该文件会公开它加载的其他模块。不过,我不确定这对本地进口产品的效果如何。非常感谢,它看起来对我有用~我明天会测试它,我马上到办公室~我会发布结果~它对我有用!非常感谢你!