作为初学python程序员,我希望这是一个有一个简单解决方案的愚蠢错误(或缺乏理解):
/tmp> python3 -c 'with open("t","r") as f: for l in f: print(l)'
File "<string>", line 1
with open("t","r") as f: for l in f: print(l)
^
SyntaxError: invalid syntax
我可以在线上嵌入换行符,但试图了解上述原因无效
/tmp> python3 -c $'with open("t","r") as f:\n for l in f: print(l)'
Hi there
答案 0 :(得分:1)
查看Full grammar specification,with
类中的simple_stmt
语句后,您允许立即放置的唯一语句是with_stmt: 'with' with_item (',' with_item)* ':' suite
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
语句。
语法的相关部分:
for
用更简洁的语言,这些陈述似乎是:
with
不属于此列表的一部分,因此不允许在numpy
之后立即出现,而且没有介入换行符。