У меня есть файл конфигурации, config.py, и я пытаюсь прочитать значение атрибута без использования importlib.import_module()
(или imp.load_source()
).
Итак, я сделал это:
# trying to just get the attribute 'comment' from the file
import ast
fd = open('config.py')
root = ast.parse(fd.read())
names = list(node for node in ast.walk(root) if isinstance(node, ast.Name) and node.id == 'comment')
print(names)
# [<_ast.Name object at 0x7fcb999048d0>]
print(names[0])
# <_ast.Name object at 0x7fcb999048d0>
print(names[0].id)
# 'comment'
print(names[0].ctx)
# <_ast.Store object at 0x7fcb9b9acbd0>
print(names[0].lineno)
# 12
print(names[0].ctx)
# <_ast.Store object at 0x7f19db3f1c10>
dir(names[0].ctx)
# ['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
# '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
# '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
# '__str__', '__subclasshook__', '__weakref__', '_attributes', '_fields']
Файл (config.py) имеет это в строке 12:
comment = "qos sample run"
И я пытаюсь выяснить, как получить это значение ("qos sample run"
) в коде,Я мог бы прочитать файл и получить строку 12, но я предполагаю, что значение хранится где-то в объекте ctx, но я просто не могу понять, где.Любая помощь приветствуется.Спасибо!