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!

1
  • Do you want to execute the function and then check imports, or do you want to do so statically with just the source code? Commented Feb 10, 2020 at 7:06

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

@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.
is there any solution that will solve my problem with my packages?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.