簡體   English   中英

python打印特定行的變量

[英]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

它沒有輸出任何輸出,請幫助。答案將不勝感激!

與其嘗試通過startswith來匹配名稱, startswith嘗試使用一些正則表達式來捕獲代表所需值的組。 嘗試使用reregex

您想要的正則表達式將類似於(未經測試的,臨時的):

self[.](\\w+)[.]set( self.(\\w+)[.]get()[+]" (You clicked the button)" )

請記住不要使用"符號。此外,您可能希望為這些組命名,這樣就可以通過名稱而不是通過組索引來獲取它們。

如果您在這種情況下不了解某些術語(例如組,正則表達式,捕獲等),請閱讀上面鏈接中的文檔,它將解釋所有內容。

如果要提取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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM