如何判断字符串是否包含有效的Python代码

asm*_*rer 18 python syntax python-3.x

如果我有一串Python代码,我如何判断它是否有效,即,如果在Python提示符下输入,它会引发一个SyntaxError?我认为使用compiler.parse可行,但显然该模块已在Python 3中删除.有没有办法可以在Python 3中运行.显然,我不想执行代码,只需检查它的语法.

phi*_*hag 20

用途ast.parse:

import ast
def is_valid_python(code):
   try:
       ast.parse(code)
   except SyntaxError:
       return False
   return True
Run Code Online (Sandbox Code Playgroud)

>>> is_valid_python('1 // 2')
True
>>> is_valid_python('1 /// 2')
False
Run Code Online (Sandbox Code Playgroud)

  • +1,但我更愿意看到`除了SyntaxError:` (3认同)