简体   繁体   English

有没有办法在python脚本中获取所有变量值?

[英]Is there a way to get all values of variables in a python script?

If this question is out of scope, please suggest where I can move it. 如果这个问题超出范围,请建议我可以移动它。

I am having a lot of python (version 2.7) scripts, which are invoking each other. 我有很多python(版本2.7)脚本,它们互相调用。 To get a view of which script calls which, I have currently built a nice GUI tree that maps this. 为了获得哪个脚本调用哪个脚本,我目前已经构建了一个很好的GUI树来映射它。

The problem I have lies within parsing the files. 我遇到的问题在于解析文件。 The simplest example of a script invoking another script is calling: 调用另一个脚本的脚本的最简单示例是调用:

os.system('another.py')

This is trivial to parse, just take what is inside the parenthesis. 解析这一点很简单,只需要考虑括号内的内容即可。 I have now come to evaluating variables. 我现在来评估变量。 My current way of evaluating variables works like this: 我目前评估变量的方式是这样的:

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

Aside from being an ugly hack, this code has its disadvantages. 除了是一个丑陋的黑客,这个代码有其缺点。 When doing the Call getVarValue to find value for every variable, then add these together not all variables get their desired value. Call getVarValue to find value for every variable, then add these together并非所有变量都获得所需的值。 For instance: 例如:

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

The problem is that I do not want to invoke these scripts (some scripts create/updates files), but rather parse them by value. 问题是我不想调用这些脚本(一些脚本创建/更新文件),而是按值解析它们。 Since the python interpreter is able to parse scripts I figure that this must be possible. 由于python解释器能够解析脚本,我认为这必须是可能的。

I have already looked in to tokenize , which gave me little help, and abstract syntax trees . 我已经查看了tokenize ,它给了我很少的帮助,以及抽象语法树 However, both of these do not seem to be able to parse variables without running the file. 但是,如果不运行该文件,这两个似乎都无法解析变量。

Is there a way (preferably pythonic) to retrieve a variable value without executing the script? 有没有办法(最好是pythonic)在不执行脚本的情况下检索变量值?

Modified from this Python3 Q&A, here is an example of using the ast module to extract a variable. 从这个Python3 Q&A修改,这是一个使用ast模块提取变量的例子。

It could be modified to extract all variables, but ast.literal_eval can only evaluate simple types. 可以修改它以提取所有变量,但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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ansible 中有没有办法让我的 python 脚本获取所有定义的变量而不将它们全部传入? - is there a way in ansible for my python script to get all the variables that are defined without passing them all in? 有什么方法可以获取所有可能的 Python 类变量,包括没有值的变量? - Any way to get all possible Python class variables, including ones without values? 获取以 python 中的特定前缀开头的所有环境变量的最佳方法 - Best way to get all environment variables starting with specific prefix in python 如何从python类中的实例变量获取所有值的列表 - How to get a list of all values from instance variables in a python class 如何在php脚本中的php变量中获取python脚本中的打印值? - How can i get the print values in python script in php variables in php script? 有没有办法让 C# 在不事先执行的情况下从 python 脚本获取和设置变量? - Is there a way to get C# to get and set variables from a python script without executing it beforehand? 有没有办法将环境变量传递给 python 脚本? - Is there a way to pass in environment variables to python script? 在运行时查看python中变量的所有值 - Seeing all the values of variables in python as it is run 获取当前范围内所有变量及其值的字典 - Get a dict of all variables currently in scope and their values 如何获取class中变量的所有值? - How to get all values of variables in class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM