⚠️ 语法站放行,语义站拦下
在函数外面写一句 return 1。让语法站(ast.parse)和语义站(compile)各判一次:
import ast, io, tokenize
def stage_of(src):
"""这段源码在流水线的哪一站被拦下来"""
try:
list(tokenize.generate_tokens(io.StringIO(src).readline))
except (tokenize.TokenError, IndentationError, SyntaxError):
return "词法"
try:
ast.parse(src)
except SyntaxError:
return "语法"
try:
code = compile(src, "<s>", "exec")
except SyntaxError:
return "语义"
try:
exec(code, {})
except NameError:
return "运行"
return "通过"
import ast
SEM = 'return 1'
ok_parse = "过" if ast.parse(SEM) else "过"
try:
compile(SEM, "<s>", "exec")
ok_compile = "过"
except SyntaxError:
ok_compile = "不过"
print(ok_parse + "/" + ok_compile)
全部评论