【问题标题】:Python how to list imports of a python functionPython如何列出python函数的导入
【发布时间】:2020-02-07 14:21:44
【问题描述】:

我在用python,需要获取一个用户函数,列出它导入了哪些模块和版本,如果我也能分析一下它导入了哪些本地脚本就更好了

我发现 this 允许这样做以获得完整的脚本,但我需要更像的东西

def a():
    import module

modules_and_versions = analyze(a) 

谢谢!

【问题讨论】:

  • 您想执行函数然后检查导入,还是只使用源代码静态地执行此操作?

标签: python python-3.x import module metaprogramming


【解决方案1】:

可以获取函数的字节码,然后解析模块名,其中opcode为“IMPORT_NAME”

import dis
from subprocess import PIPE, run



def a():
    import pandas




bytecode = dis.Bytecode(a)

modules = [instr.argval for instr in bytecode if instr.opname == "IMPORT_NAME"]

for module in modules:
    command = f"pip show {module} | grep Version"
    result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
    print(module, result.stdout)

【讨论】:

  • @thebeancounter 编辑了代码以显示版本。但是,对于您创建的模块可能无法正常工作,请使用适当的异常处理。
  • 有什么解决方案可以解决我的包裹问题吗?
  • 仅当您的包包含版本信息并且它们已上传到 pypi 时。此外,如果它们是您的软件包,那么当然,您可以构建一些方法来从中获取版本
猜你喜欢
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 2020-01-10
  • 2020-05-08
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多