我想检查输入是否是Python代码

问题描述 投票:0回答:1

我想在将输入连接到更大的变量以最终执行之前检查输入是否是代码,有什么办法可以做到这一点吗? 例如:

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

那样工作
python python-2.7 exec python-2.x
1个回答
3
投票

您可以尝试使用

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)

如果字符串不可解析(包含无效的 Python 代码),该函数将引发

SyntaxError

© www.soinside.com 2019 - 2024. All rights reserved.