Is there a way to get all the values ​​of variables in a python script?

If this question is beyond the scope, please suggest where I can move it.

I have many python scripts (version 2.7) that call each other. To get an idea of ​​what the script calls that I currently created a beautiful graphical interface tree that displays this.

The problem I ran into is analyzing the files. The simplest example of a script calling another script calls:

os.system('another.py')

This is trivial to parse, just take what's inside the parenthesis. Now I have come to evaluate variables. My current way of evaluating variables works as follows:

x = 'another'
dot = '.'
py = 'py'
os.system(x+dot+py) # Find three variables

listOfVars = getVarsBetweenParenthesis() # Pseudo code.

# Call getVarValue to find value for every variable, then add these together 

'''
    Finds the value of a variable.
'''
def getVarValue(data, variable, stop):
    match = ''
    for line in data:
        noString = line.replace(' ', '') # Remove spaces
        if variable+'=' in noString:
            match = line.replace(variable+'=', '').strip()
        if line == stop:
            break
    return match

, . Call getVarValue to find value for every variable, then add these together . :

x = os.getcwd() # Cannot be found by getVarValue
script = 'x.py'
os.system(x+script) # Find three variables

, ( / ), . python , , .

tokenize, , . , , , .

( pythonic) script?

+4
1

Python3 Q & A, ast- .

, 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") as file_mod:
        data = file_mod.read()

    try:
        ast_data = ast.parse(data, filename=mod_path)
    except:
        if raise_exception:
            raise
        print("Syntax error 'ast.parse' can't read %r" % mod_path)
        import traceback
        traceback.print_exc()

    if ast_data:
        for body in ast_data.body:
            if body.__class__ == ast.Assign:
                if len(body.targets) == 1:
                    print(body.targets[0])
                    if getattr(body.targets[0], "id", "") == variable:
                        try:
                            return ast.literal_eval(body.value)
                        except:
                            if raise_exception:
                                raise
                            print("AST error parsing %r for %r" % (variable, mod_path))
                            import traceback
                            traceback.print_exc()
    return default

# example use
this_variable = {"Hello": 1.5, 'World': [1, 2, 3]}
that_variable = safe_eval_var_from_file(__file__, "this_variable")
print(this_variable)
print(that_variable)
+1

Source: https://habr.com/ru/post/1546521/


All Articles