Copy-paste into Python interactive interpreter and indentation

前端 未结 8 1650
借酒劲吻你
借酒劲吻你 2020-12-06 00:41

This piece of code, file test.py,

if 1:
   print \"foo\"
print \"bar\"

can be successfully executed with execfile(\"test.py\

相关标签:
8条回答
  • 2020-12-06 01:04

    If the pasted content has any empty lines, the interpreter triggers evaluation when encountering them. If any line after an empty line has indentation, it will cause an IndentationError since any previous context has been closed.

    Solutions:

    • Delete any empty lines before copying to clipboard.
    • Add any amount of indentation to empty lines (doesn't need to match code) before copying to clipboard.

    Note that spaces vs. tabs does not seem to matter.

    0 讨论(0)
  • 2020-12-06 01:13

    Continuation lines are needed when entering a multi-line construct. --Interactive mode, The Python Tutorial (v2) (v3)

    So you need to enter:

    if 1:
       print "foo"
    
    print "bar"
    

    I've yet to find a suitable explanation as to why it's different to a non-interactive session, alas.

    0 讨论(0)
提交回复
热议问题