我想在将输入连接到较大变量以最终执行之前检查输入是否为代码,有什么办法可以做到这一点?例如:
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
但是我不知道像这样的命令 .iscode()
您可以尝试使用解析输入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)
SyntaxError
如果字符串不可解析(包含无效的Python代码),则该函数将引发a 。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句