[英]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.