gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:51:56 35 4
gpt4 key购买 nike

如果这个问题超出了范围,请建议我可以将它移到哪里。

我有很多 python(2.7 版)脚本,它们相互调用。查看哪个脚本调用它,我目前已经构建了一个很好的 GUI 树来映射它。

我的问题在于解析文件。一个脚本调用另一个脚本的最简单示例是调用:

os.system('another.py')

解析起来很简单,只需要括号内的内容即可。我现在开始评估变量。我目前评估变量的方式是这样的:

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

除了是一个丑陋的 hack 之外,这段代码也有它的缺点。做的时候调用 getVarValue 来查找每个变量的值,然后将它们相加 并非所有变量都获得所需的值。例如:

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

问题是我不想调用这些脚本(一些脚本创建/更新文件),而是按值解析它们。由于 python 解释器能够解析脚本,我认为这一定是可能的。

我已经查看了 tokenize ,这对我帮助不大,并且 abstract syntax trees .但是,这两者似乎都无法在不运行文件的情况下解析变量。

有没有办法(最好是 pythonic)在不执行脚本的情况下检索变量值?

最佳答案

修改自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)

关于python - 有没有办法在 python 脚本中获取变量的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24486071/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com