How to tell if a string contains valid Python code

后端 未结 2 1168
再見小時候
再見小時候 2020-11-30 10:12

If I have a string of Python code, how do I tell if it is valid, i.e., if entered at the Python prompt, it would raise a SyntaxError or not? I thought that using comp

2条回答
  •  悲哀的现实
    2020-11-30 10:22

    The compiler module is now a built-in.

    compile(source, filename, mode[, flags[, dont_inherit]])
    

    Compile the source into a code or AST object. Code objects can be executed by an exec statement or evaluated by a call to eval(). source can either be a string or an AST object. Refer to the ast module documentation for information on how to work with AST objects.

    The AST parser is now a seperate module.

    ast.parse(expr, filename='', mode='exec')
    

    Parse an expression into an AST node. Equivalent to compile(expr, filename, mode, ast.PyCF_ONLY_AST).

提交回复
热议问题