简体   繁体   中英

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()

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM