Last active
May 12, 2020 12:29
-
-
Save shakram02/f5ab465ed9dce1164242d57d47fa93ee to your computer and use it in GitHub Desktop.
Convert python string to callable code. Import a module without executing it's main() / or expressions. Just the definitions and imports.
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 ast | |
func_h = """ | |
import socket | |
class Toroto: | |
def __init__(self): | |
self.quacks = 0 | |
def quack(self): | |
self.quacks += 1 | |
print(self.quacks, "Quacks") | |
def h(): | |
t = Toroto() | |
print("Hello") | |
for i in range(3): | |
t.quack() | |
def w(): | |
print("World") | |
print("NOTOTOTOTOT") | |
""" | |
tree = ast.parse(func_h) | |
# https://stackoverflow.com/questions/48759838/how-to-create-a-function-object-from-an-ast-functiondef-node | |
# https://stackoverflow.com/questions/23801672/python-ast-ast-nodetransformer-typeerror-required-field-lineno-missing-from | |
# https://stackoverflow.com/questions/57897223/how-to-compile-ast-node-in-eval-mode | |
print(ast.dump(tree)) | |
cleaned_up = ast.Module(body=[]) | |
for node in tree.body: | |
# We don't want to execute loose code under if __name__ == "__main__" | |
# or whatever. We just need the function definitions. | |
if type(node) in [ast.FunctionDef, ast.Import, ast.ImportFrom, ast.ClassDef]: | |
cleaned_up.body.append(node) | |
code = compile(cleaned_up, filename="", mode="exec") | |
namespace = {} | |
print() | |
print(ast.dump(cleaned_up)) | |
exec(code, namespace) | |
namespace['h']() | |
# namespace['w']() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment