有没有办法在python脚本中获取所有变量值?
发布时间:2020-12-20 13:43:22 所属栏目:Python 来源:网络整理
导读:如果这个问题超出范围,请建议我可以移动它. 我有很多python(版本2.7)脚本,它们互相调用.获取哪个脚本的视图 调用哪些,我目前已经构建了一个很好的GUI树来映射它. 我遇到的问题在于解析文件.调用另一个脚本的脚本的最简单示例是调用: os.system('another.py'
如果这个问题超出范围,请建议我可以移动它.
我有很多python(版本2.7)脚本,它们互相调用.获取哪个脚本的视图 我遇到的问题在于解析文件.调用另一个脚本的脚本的最简单示例是调用: 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 除了是一个丑陋的黑客,这个代码有其缺点.做的时候 x = os.getcwd() # Cannot be found by getVarValue script = 'x.py' os.system(x+script) # Find three variables 问题是我不想调用这些脚本(一些脚本创建/更新文件),而是按值解析它们. 我已经看过tokenize,这给了我很少的帮助,abstract syntax trees. 有没有办法(最好是pythonic)在不执行脚本的情况下检索变量值? 解决方法
这里从这个
Python3 Q&A,修改了一个使用ast模块提取变量的例子.
可以修改它以提取所有变量,但ast.literal_eval只能评估简单类型. def safe_eval_var_from_file(mod_path,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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |