I would like to check if an input is python code
Question: 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()`


Answer: You could try parsing the input with
[`ast.parse`](https://docs.python.org/3/library/ast.html#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).

