1

I have this piece of code:

import code

interpreter = code.InteractiveInterpreter()
myCode = code.compile_command('if True: print("IT\'S TRUE!!")')
interpreter.runcode(myCode)

I'm wondering, what is the difference between InteractiveInterpreter.runcode() and a normal exec() function? The code above doesn't work, but this one does:

exec("if True: print('IT\'S TRUE!!')")

1 Answer 1

1
>>> import code
>>> 
>>> interpreter = code.InteractiveInterpreter()
>>> myCode = code.compile_command('if True: print("IT\'S ONE!!")')
>>> interpreter.runcode(myCode)
TypeError: exec: arg 1 must be a string, file, or code object

It's obvious that interpreter.runcode accept string or code.

But myCode is None.

>>> myCode
>>> 

According to code.compile_command documentation:

... Returns a code object (the same as compile(source, filename, symbol)) if the command is complete and valid; None if the command is incomplete; raises SyntaxError if the command is complete and contains a syntax error, or raises OverflowError or ValueError if the command contains an invalid literal.

If you pass a string to interpreter.runcode, it works.

>>> interpreter.runcode('if True: print("IT\'S ONE!!")')
IT'S ONE!!
Sign up to request clarification or add additional context in comments.

4 Comments

so myCode isn't a file object?
@aIKid, It's is None, not a file object.
Sorry, typo. I mean, it's not a code object? I thought code.compile_command() should return a code object.
@aIKid, If you do code.compile_command('if True: print("IT\'S ONE!!")\n'), you will get code object. (Appending newline character)

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.