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

标签 python syntax runtime-error

考虑这个代码:

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

最佳答案

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

>>> with open('/dev/random') as fin :
...     print(0)
...                             <<--- an empty line
0
>>> print(1)
1
>>> 

关于python - 为什么我的代码在 .py 文件中运行时可以工作,但在 Python 解释器中返回 SyntaxError ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61586186/

相关文章:

javascript - 网页运行时错误

mysql - 检查存储过程是否包含正确的表名

Python Boto3 : Error when trying to download files from AWS S3

Python:正确分配测试描述符

haskell - 无法将预期类型 [a0] 与实际类型 IO () 匹配

Javascript 和 jquery 语法

java - 套接字中的 UnknownHostException

python - 如何删除Python中两个特定单词之间的文本

Python 和 Json

powershell - 高级语法