1

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!

thebeancounter
  • 4,261
  • 8
  • 61
  • 109
  • Do you want to execute the function and then check imports, or do you want to do so statically with just the source code? – MisterMiyagi Feb 10 '20 at 07:06

1 Answers1

1

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)
Eternal
  • 928
  • 9
  • 22
  • @thebeancounter edited the code to display versions also. However for modules that are created by you might not work properly with this, use proper exception handling. – Eternal Feb 10 '20 at 06:35
  • is there any solution that will solve my problem with my packages? – thebeancounter Feb 10 '20 at 07:36
  • Only if your packages contain version info and if they are uploaded to pypi. Also if they are your packages then, of course, you can build some method to get the versions out of them – Eternal Feb 10 '20 at 07:39