最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Exec in Python not capturing output - Stack Overflow

programmeradmin3浏览0评论

exec("a=1\nprint(a)") prints 1, as expected. However exec("a=1\na") does not print out 1. Why is that?

I expect it to print out 1 because in the Python interpreter, whenever I enter a variable name, it prints out its value:

>>> a = 1
>>> a
1

exec("a=1\nprint(a)") prints 1, as expected. However exec("a=1\na") does not print out 1. Why is that?

I expect it to print out 1 because in the Python interpreter, whenever I enter a variable name, it prints out its value:

>>> a = 1
>>> a
1
Share Improve this question edited Jan 18 at 22:03 wjandrea 32.9k9 gold badges69 silver badges96 bronze badges asked Jan 18 at 22:01 ijustwantedtosayhiijustwantedtosayhi 297 bronze badges 4
  • 2 Did you read the docs about exec()? e.g. this part: "The return value is None." – wjandrea Commented Jan 18 at 22:07
  • Why are you expecting it to behave like the REPL? – wjandrea Commented Jan 18 at 22:10
  • 1 I know the return value is None, I just expected it to show me the same output as a print ("asd") would. But now that you said that, it occurs to me that int is a class, and I guess in the Python interpreter when I enter any variable or a literal integer, it returns that value and that's why it appears there. In which case, it makes sense that exec doesn't show me the value. I didn't realize why the interpreter showed back the value I typed into it, but if it's a return value, then yeah... I could also use eval. Thanks for the help! – ijustwantedtosayhi Commented Jan 18 at 22:12
  • exec works the same as a .py script. If we write a 2 line .py file without the print, we wouldn't expect it to print anything. – tdelaney Commented Jan 18 at 22:44
Add a comment  | 

1 Answer 1

Reset to default 0

This is because exec() always run the code via execution, not interpreter. If you want to print like an interpreter, than you can use eval:

>>> a = 1
>>> eval("a")
1
>>>
发布评论

评论列表(0)

  1. 暂无评论