如何判断字符串是否包含有效的 Python 代码 [英] How to tell if a string contains valid Python code
本文介绍了如何判断字符串是否包含有效的 Python 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个 Python 代码字符串,我如何判断它是否有效,即,如果在 Python 提示符下输入,它是否会引发 SyntaxError?我认为使用 compiler.parse
会工作,但显然该模块已在 Python 3 中删除.有没有办法做到这一点,也适用于 Python 3.显然,我不想执行代码,只需检查其语法.
解决方案
使用 <代码>ast.parse:
导入 astdef is_valid_python(代码):尝试:ast.parse(代码)除了语法错误:返回错误返回真
<预><代码>>>>is_valid_python('1//2')真的>>>is_valid_python('1///2')错误的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 compiler.parse
would work, but apparently that module has been removed in Python 3. Is there a way to do it that also works in Python 3. Obviously, I don't want to execute the code, just check its syntax.
解决方案
Use ast.parse
:
import ast
def is_valid_python(code):
try:
ast.parse(code)
except SyntaxError:
return False
return True
>>> is_valid_python('1 // 2')
True
>>> is_valid_python('1 /// 2')
False
这篇关于如何判断字符串是否包含有效的 Python 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文