首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python模块无法检测"if“或"for”

Python模块无法检测"if“或"for”
EN

Stack Overflow用户
提问于 2014-09-22 06:59:14
回答 2查看 1.6K关注 0票数 1

我试图用以下访问者限制用户提供的脚本:

代码语言:javascript
运行
复制
class SyntaxChecker(ast.NodeVisitor):

    def check(self, syntax):
        tree = ast.parse(syntax)
        print(ast.dump(tree), syntax)
        self.visit(tree)

    def visit_Call(self, node):
        print('Called for Call', ast.dump(node))
        if isinstance(node.func, ast.Call) and node.func.id not in allowed_functions:
            raise CodeError("%s is not an allowed function!"%node.func.id)
        elif isinstance(node.func, ast.Attribute) and node.func.value.id not in allowed_classes:
            raise CodeError('{0} is not calling an allowed class'.format(node.func.value.id))
        elif isinstance(node.func, ast.Name) and node.func.id in allowed_classes:
            raise CodeError('You are not allowed to instantiate any class, {0}'.format(node.func.id))
        else:
            ast.NodeVisitor.generic_visit(self, node)

    def visit_Assign(self, node):
        print('Called for Assign', ast.dump(node))
        ast.NodeVisitor.generic_visit(self, node)

    def visit_Attribute(self, node):
        print('Called for Attribute', ast.dump(node))
        if node.value.id not in allowed_classes:
            raise CodeError('"{0}" is not an allowed class'.format(node.value.id))
        elif node.value.id in allowed_classes and isinstance(node.ctx, ast.Store):
            raise CodeError('Trying to change something in a pre-defined class, "{0}" in "{1}"'.format(node.attr, node.value.id))
        else:
            ast.NodeVisitor.generic_visit(self, node)

    def visit_Expr(self, node):
        print('Called for Expr', ast.dump(node))
        ast.NodeVisitor.generic_visit(self, node)

    def visit_Name(self, node):
        print('Called for Name', ast.dump(node))
        if isinstance(node.ctx, ast.Store) and node.id in allowed_classes:
            raise CodeError('Trying to change a pre-defined class, {0}'.format(node.id))
        elif isinstance(node.ctx, ast.Load) and node.id not in safe_names and node.id not in allowed_functions and node.id not in allowed_classes:
            raise CodeError('"{0}" function is not allowed'.format(node.id))
        else:
            ast.NodeVisitor.generic_visit(self, node)

    def generic_visit(self, node):
        print('Called for generic', ast.dump(node))        
        if type(node).__name__ not in allowed_node_types:
            raise CodeError("%s is not allowed!"%type(node).__name__)
        else:
            ast.NodeVisitor.generic_visit(self, node)

if __name__ == '__main__':
    # Check whole file
    x = SyntaxChecker()
    code = open(sys.argv[1], 'r').read()
    try:
        x.check(code)
    except CodeError as e:
        print(repr(e))

    # Or check line by line, considering multiline statements
    code = ''
    for line in open(sys.argv[1], 'r'):
        line = line.strip()
        if line:
            code += line
            try:
                print('[{0}]'.format(code))
                x.check(code)
                code = ''
            except CodeError as e:
                print(repr(e))
                break
            except SyntaxError as e:
                print('********Feeding next line', repr(e))

它暂时做得很好,我会对它进行更多的调优,但问题是,在解析类似的东西时,这总是抛出SyntaxError('unexpected EOF while parsing', ('<unknown>', 1, 15, 'for j in A.b():'))

代码语言:javascript
运行
复制
for j in A.b():
    print('hey')

正因为如此,没有任何forif被解析。

编辑:我增加了一次检查整个代码的代码,或者检查多行语句.

EN

Stack Overflow用户

发布于 2018-03-08 22:33:14

您可以使用is实例(迭代器,(Ast,if,Ast.For)使用ast.parse进行解析。

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25968247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档