为什么我的代码在.py文件中运行时可以工作,但在Python解释器中却返回一个SyntaxError?

问题描述 投票:4回答:1

考虑一下这段代码。

with open("tmp", "w") as f:
    print(0)
print(1)

这段代码在保存为 bug.py 并与 python bug.py. 但我无法将这段代码复制粘贴到python解释器中。

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("tmp", "w") as f:
...     print(0)
... print(1)
  File "<stdin>", line 3
    print(1)
    ^
SyntaxError: invalid syntax
>>>

语法错误在哪里?

编辑。 这适用于更普遍的情况,比如

if False:
    pass
pass
python syntax runtime-error
1个回答
6
投票

你需要一个额外的空行来结束你的 with 语句,并输入下一个 print 声明:

>>> with open('/dev/random') as fin :
...     print(0)
...                             <<--- an empty line
0
>>> print(1)
1
>>> 
© www.soinside.com 2019 - 2024. All rights reserved.