python - 我想检查输入是否是 python 代码

标签 python python-2.7 exec python-2.x

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

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)

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

关于python - 我想检查输入是否是 python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705490/

相关文章:

c - c中的Execl(传递参数)

python - 属性错误 : 'module' object has no attribute python

python - 将列表发布到 django rest api

google-app-engine - 运行 Google App Engine 测试项目时出现 ImportError

python - Pyqt 鼠标悬停在 QPushButton 上

python - 如何查找并替换txt文件中的属性?

python - 使用 Python 和 Pandas 访问 JSON 元素

python - SQLAlchemy 事件注册

java - 使用 JSCH、apache mina sshd 或 sshj 的 Open SSH 的 SSH Exec channel

c - 在 exec() 之后,child 继承了文件描述符,但流可能无法访问?