0

I'm trying to extract all the "runnable" code given a function in a module. Right now I'm only able to extract the functions in any imported module that are called inside the starting function. However, some modules have "outside" expressions (i.e. some variables defined globally in the module, or functions called in the same level).

With inspect and dis I did the work to extract the functions, but, is there any way of extracting the "non-function" of a module?


If anybody wonders what am I doing, is a packer for python. What I want to achieve is that this tools only packs the required code given a starting function.

Also, if is there something already out there that does what I'm trying to achieve, I'd like to know.

martineau
  • 119,623
  • 25
  • 170
  • 301
dnarvaez27
  • 472
  • 1
  • 6
  • 10

1 Answers1

0

importing a module as a code object

You can use importlib's get_code() method which returns the code object of the module and then you can modify or create a new code object extracting the required parts. exec method can be used for executing code object.

Alternatively, using the built-in compile function, you can directly compile source code into byte code then follow the same procedure as mentioned above.

References:

Modifying python bytecode
assembling-python-module-on-fly-dynamic-import

hack3r-0m
  • 700
  • 6
  • 20