2017-04-10 21 views
2

作爲一個初學者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 
+1

爲什麼不'print'\ n'.join(l for l in open(「t」))'? –

+0

在同一行中不能有兩個*語句*。 –

+1

或http://stackoverflow.com/questions/2043453/executing-python-multi-line-statements-in-the-one-line-command-line –

回答

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之後沒有插入換行符。