If statements and one line python scripts from command line

后端 未结 4 1236
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 16:17

Why do I receive a syntax error for the following one liner python code?

python -c \'import re; if True: print \"HELLO\";\'
  File \"\", line 1         


        
4条回答
  •  [愿得一人]
    2020-12-20 16:46

    Why do I receive a syntax error for the following one liner python code?

    Python grammar might forbid small_stmt ';' compound_stmt. -c argument is probably is interpreted as file_input:

    fileinput: (NEWLINE | stmt)* ENDMARKER
    stmt: simple_stmt | compound_stmt
    simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
    small_stmt: import_stmt 
    compound_stmt: if_stmt 
    

    Note: there is a newline at the end of simple_stmt. if_stmt is not small_stmt it can't follow another small_stmt after ';'. A newline is necessary to introduce compound_stmt after small_stmt.

    It is not an issue because bash allows multiline arguments, just don't close the opening single quote until you done e.g.:

    $ python -c '
    > import re
    > if 1:
    >   print(1)
    > '
    1
    

    Note: > are printed by the shell itself here. It is not entered by hand.

提交回复
热议问题