2014-06-30 60 views
4

如果这个问题超出范围,请建议我可以在哪里移动它。有没有办法在python脚本中获取所有变量值?

我有很多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 

除了是一个丑陋的黑客攻击,该代码有它的缺点。在执行 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,这给了我一点帮助,abstract syntax trees。 但是,这两种方法似乎都无法在不运行文件的情况下解析变量。

有没有一种方法(最好是pythonic)检索变量值而不执行脚本?

+0

想想你在问什么:如果变量的值在脚本执行后发生变化,你想显示什么?初始值,还是计算值? –

+0

我不确定,但你有没有尝试monkeypatching'os.system'?如此操作:'os.system = lambda script_name:send_script_name_to_where_you_collect_them(script_name'。 – J0HN

+0

@BurhanKhalid:嗯,好问题!我想查找所有值,以便我可以找到所有正在调用的脚本。 – Pphoenix

回答

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) 
+0

完美的解决方案,像一个魅力工作! – Pphoenix

相关问题