I am using a 3rd party application’s Python integration where Python code is stored internally in binary files. So I want to separate the code from it. I could create a module but the code I need to include doesn’t function on its own, as it includes locals only valid in that context, etc.
I am basically looking for a copy-paste solution at compile-time.
Is there any way to do this in Python?
Yes, it’s called
exec.Your code would look like this:
exec your_code_str. The code is then executed in the current scope.You could also specify a different scope:
exec your_code_str in globals(), locals()(those values are the default, so only specify them if they differ)Note that you can also pass a file object, so if the python code is only a single blob of text right at the end of the binary file you can just seek to the beginning of the code and then pass the file object.