parser.py 文件源码

python
阅读 20 收藏 0 点赞 0 评论 0

项目:topology 作者: HPENetworking 项目源码 文件源码
def find_topology_in_python(filename):
    """
    Find the TOPOLOGY variable inside a Python file.

    This helper functions build a AST tree a grabs the variable from it. Thus,
    the Python code isn't executed.

    :param str filename: Path to file to search for TOPOLOGY.
    :rtype: str or None
    :return: The value of the TOPOLOGY variable if found, None otherwise.
    """
    import ast

    try:
        with open(filename) as fd:
            tree = ast.parse(fd.read())

        for node in ast.iter_child_nodes(tree):
            if not isinstance(node, ast.Assign):
                continue
            if node.targets[0].id == 'TOPOLOGY':
                return node.value.s

    except Exception:
        log.error(format_exc())
    return None
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号