python打印特定行的变量
我想打印python文件特定行中的变量 假设我的文件有一行:python打印特定行的变量,python,Python,我想打印python文件特定行中的变量 假设我的文件有一行: self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" ) 输出必须是: labelvariable entryvariable 我尝试了一个程序: import os import re with open('adapt.py', 'r') as my_file: for vars in dir(): f
self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" )
输出必须是:
labelvariable
entryvariable
我尝试了一个程序:
import os
import re
with open('adapt.py', 'r') as my_file:
for vars in dir():
for line in my_file:
if vars.startswith("self.") == 0:
print vars
它打印我没有输出,请帮助。答案将不胜感激 不要尝试通过
startswith
来匹配名称,而是尝试使用一些正则表达式来捕获表示所需值的组。尝试使用或
您想要的正则表达式类似于(未经测试,临时编写):
self[.](\w+[.]设置(self)(\w+[.]get()[+](您单击了按钮)
请记住转义“
符号。此外,您可能需要命名这些组,以便可以按名称而不是按组索引获取它们
如果您不知道此上下文中的某些术语(如组、正则表达式、捕获等)-请阅读上面链接中的文档-它将解释一切。如果您想提取
self
上的所有属性,最好实际解析文件。此处可以提供帮助
子类化以查找ast.Attribute
节点,并在这些节点的value
一侧测试self
名称:
class SelfAttributesVisitor(ast.NodeVisitor):
def __init__(self):
self.attributes = []
def visit_Attribute(self, node):
if isinstance(node.value, ast.Name) and node.value.id == 'self':
self.attributes.append(node.attr)
else:
self.visit(node.value)
然后将结果传递到:
演示您的有限示例:
>>> import ast
>>> source = 'self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" )'
>>> ast_tree = ast.parse(source, 'adapt.py')
>>> visitor = SelfAttributesVisitor()
>>> visitor.visit(ast_tree)
>>> visitor.attributes
['labelVariable', 'entryVariable']
我的猜测是,与
if vars.startswith(“self”)==0:
不同,您需要if line.startswith(“self”)==0:
。行上是否有任何前导空格?例如,行是否像Python程序中通常那样缩进?您还假设vars()
将对文本文件进行操作;这是一个错误的假设。文本文件不会被解析为Python。如何将其打印/显示为输出?我的意思是如何使用print stmt进行显示?您是否可以根据我的问题修改您的程序?那么,类SelfAttributesVisitor(ast.NodeVisitor)是否应该:必须在解析之前提供给adapt.py?@adarshram:您需要在代码中包含该类,以便可以实例化它。@adarshram:然后读取adapt.py
,将文本传递给ast.parse()
,然后使用自定义节点遍历器处理生成的解析树(抽象语法树)。
>>> import ast
>>> source = 'self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" )'
>>> ast_tree = ast.parse(source, 'adapt.py')
>>> visitor = SelfAttributesVisitor()
>>> visitor.visit(ast_tree)
>>> visitor.attributes
['labelVariable', 'entryVariable']