2

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/YAML/TOML is better suited, there are times when its useful to do this.

How can variable names & values be extracted from a Python script without executing it?
(assuming the values construction doesn't contain code-execution for their creation)

1 Answer 1

5

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().

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

    try:
        ast_data = ast.parse(data, filename=mod_path)
    except Exception as ex:
        if raise_exception:
            raise
        print("AST error ({!r}), {!r}, {!r}".format(ex, mod_path))
        ast_data = None

    if ast_data is not None:
        for body in ast_data.body:
            if body.__class__ == ast.Assign:
                if len(body.targets) == 1:
                    if getattr(body.targets[0], "id", "") == variable:
                        try:
                            return ast.literal_eval(body.value)
                        except Exception as ex:
                            if raise_exception:
                                raise
                            print("AST error ({!r}) {!r} for {!r}".format(
                                ex, variable, mod_path,
                            ))
    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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.