with ... : for ... : 在一行中

with ... : for ... : in a single line

作为初学者 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

我可以在 oneline 中嵌入一个换行符,但试图理解为什么上面的方法不起作用

/tmp> python3 -c $'with open("t","r") as f:\n for l in f: print(l)'
Hi there

查看 Full grammar specification,您可以在同一行的 with 语句之后立即放置的唯一语句是 simple_stmt [=50= 中的语句].

语法相关部分:

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

用更通俗的语言来说,这些陈述似乎是:

  • 表达式语句
  • 删除
  • 及格
  • 中断
  • 继续
  • return
  • 提高
  • 产量
  • 进口
  • 全球
  • 非本地
  • 断言

for 不是此列表的一部分,因此不允许紧接在 with 之后且中间没有换行符。