[英]I would like to check if an input is python code
I would like to check if an input is code before joining it to a larger variable to eventually execute, is there any way I can do this? 我想在将输入连接到较大的变量以最终执行之前检查输入是否为代码,有什么办法可以做到这一点? For example:
例如:
import readline
while True:
codelines=[]
code=raw_input(">>> ")
if code.iscode():
codelines.append(code)
elif x=="end":
break
else:
print "Not usable code."
fullcode="\n".join(codelines)
try:
exec fullcode
except Exception, e:
print e
But I know of no command that works like .iscode()
但是我不知道像
.iscode()
这样的命令
You could try parsing the input with ast.parse
: 您可以尝试使用
ast.parse
解析输入:
import ast
while True:
codelines=[]
code=raw_input(">>> ")
try:
ast.parse(code) # Try to parse the string.
except SyntaxError:
if x=="end": # If we get here, the string contains invalid code.
break
else:
print "Not usable code."
else: # Otherwise, the string was valid. So, we add it to the list.
codelines.append(code)
The function will raise a SyntaxError
if the string is non-parseable (contains invalid Python code). 如果字符串不可解析(包含无效的Python代码),则该函数将引发
SyntaxError
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.