Issue
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()
Solution
You could try parsing the input with 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).
Answered By - user2555451
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.