Skip to content Skip to sidebar Skip to footer

How To Extract Variables In A Python Script Without Executing It?

In some cases its useful to read data from a Python script (which may be from an un-trusted source), and extract values from it. Even though in most cases a format such as XML/JSON

Solution 1:

This can be done using Python's ast module:

This example function reads a single named variable from a file.

Of course this requires the variable can be evaluated using ast.literal_eval().

defsafe_eval_var_from_file(mod_path, variable, default=None, *, raise_exception=False):
    import ast
    ModuleType = type(ast)
    withopen(mod_path, "r", encoding='UTF-8') as file_mod:
        data = file_mod.read()

    try:
        ast_data = ast.parse(data, filename=mod_path)
    except:
        if raise_exception:
            raiseprint("Syntax error 'ast.parse' can't read %r" % mod_path)
        import traceback
        traceback.print_exc()
        ast_data = Noneif ast_data:
        for body in ast_data.body:
            if body.__class__ == ast.Assign:
                iflen(body.targets) == 1:
                    ifgetattr(body.targets[0], "id", "") == variable:
                        try:
                            return ast.literal_eval(body.value)
                        except:
                            if raise_exception:
                                raiseprint("AST error parsing %r for %r" % (variable, mod_path))
                            import traceback
                            traceback.print_exc()
    return default


# Example use, read from ourself :)
that_variable = safe_eval_var_from_file(__file__, "this_variable")
this_variable = {"Hello": 1.5, b'World': [1, 2, 3], "this is": {'a set'}}
assert(this_variable == that_variable)

Post a Comment for "How To Extract Variables In A Python Script Without Executing It?"