-
-
Save mikalv/68bfcf917f6b5e8b7e8bb5f05cdf3c8f to your computer and use it in GitHub Desktop.
A proof-of-concept function that extract import statements from Python bytecode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dis | |
import inspect | |
def extract_imports(code): | |
"""Returns list of pairs (module_name, from_list) representing imports | |
from a given code object.""" | |
i = 0 | |
n = len(code.co_code) | |
IMPORT_NAME = dis.opmap['IMPORT_NAME'] | |
LOAD_CONST = dis.opmap['LOAD_CONST'] | |
result = [] | |
last_const = None | |
while i < n: | |
op = ord(code.co_code[i]) | |
# handle arguments if present | |
arg = None | |
if op >= dis.HAVE_ARGUMENT: | |
# FIXME: this doesn't support EXTENDED_ARG | |
arg = ord(code.co_code[i+1]) + ord(code.co_code[i+2])*256 | |
i = i+3 | |
else: | |
i = i+1 | |
if op == IMPORT_NAME: | |
result.append((code.co_names[arg], last_const)) | |
elif op == LOAD_CONST: | |
last_const = code.co_consts[arg] | |
return result | |
code = inspect.stack()[1][0].f_code | |
print extract_imports(code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment