[英]python print variables of a specific line
我想從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():
for line in my_file:
if vars.startswith("self.") == 0:
print vars
它沒有輸出任何輸出,請幫助。答案將不勝感激!
如果要提取self
上的所有屬性,最好實際解析該文件。 ast
模塊可以在這里提供幫助。
子類化ast.NodeVisitor
實用程序類以查找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)
然后將ast.parse()
的結果傳遞給它:
with open('adapt.py', 'r') as my_file:
source = my_file.read()
ast_tree = ast.parse(source, 'adapt.py')
visitor = SelfAttributesVisitor()
visitor.visit(ast_tree)
print visitor.attributes
演示有限示例:
>>> 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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.