简体   繁体   English

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

[英]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() 但是我不知道像.iscode()这样的命令

You could try parsing the input with ast.parse : 您可以尝试使用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). 如果字符串不可解析(包含无效的Python代码),则该函数将引发SyntaxError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我想用 python 检查物理端口冗余检查 - I would like to check physical ports redunducy check with python 我想检查传入的文件(导入的文件)是否是 python 中的 .csv 或 .xls 或 .xlxs - I would like to check if an incoming file (the imported file) is a .csv or .xls or .xlxs in python 我想更好地理解这段代码 - Please I would like to understand this code better 使用 Python argparse,如果未指定我的输出文件的名称,我希望使用输入文件的名称 - Using Python argparse, if the name of my output file is not specified, I would like the input file’s name to be used 我将如何对这样的代码进行单元测试? - How would I unit test code like this? 多处理:我想更好地理解这段代码 - Multiprocessing: I would like to understand this code better 我想打印一个字母模式,如果有什么东西可以即兴创作我用 python 编写的代码 - I want to print a pattern of letters and would like if there is something to improvise the code I have written in python 我想知道这在python中是否可行 - I would like to know if this is possible in python 我想用 Python 中的字母替换单词 - I Would Like To Replace A Word With A Letter In Python python,openCv,链代码->我想找到这些点之间的角度 - python, openCv, chain code -> i would like to find angles between the points
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM