thebeancounter
thebeancounter

Reputation: 4849

Python how to list imports of a python function

I am using python and need to get a user function and list what modules and versions it imports, If I can also analyze what local scripts it imports, it will be better

I found this Alowing to do so for a full script, but I need something that is more like

def a():
    import module

modules_and_versions = analyze(a) 

Thanks!

Upvotes: 1

Views: 68

Answers (1)

Eternal
Eternal

Reputation: 933

You can get the byte code of the function and then parse the module name where opcode is "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)

Upvotes: 1

Related Questions