Reputation: 28302
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!!')")
Upvotes: 1
Views: 470
Reputation: 369364
>>> 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!!
Upvotes: 1