2

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

1
  • 2
    I would be VERY careful allowing a user to enter code that will be run. I would recommend removing certain words like import from any entered text. To avoid things like this __import__('os').system('rm -rf /') from being run. Commented Nov 2, 2014 at 23:19

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

Of course, you are aware that accepting user input and executing it (whether in Python or sql or whatever) is just a massive security risk? Especially with Python which can easily do something very nasty by invoking system level commands. "import shutil; shutil.rmtree("~")", for example.
I just want to reiterate what @JLPeyret said. It is EXTREMELY risky to accept user input that will be run.
+1 for @JLPeyret - if your design needs arbitrary input of python code, rethink your design - maybe implementing a subset ...
The documentation says it creates a code object which can be passed to exec. Does that mean it isn't executed? And the failure is purely syntactical?
@PeterWood - Yes, that is correct. ast.parse will not execute the string, only parse it into a code object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.