Syntax error with Python one-liner

前端 未结 2 1996
执念已碎
执念已碎 2020-12-10 15:43
python -c \'import sys; print \"a\"\'

works, and

python -c \'for a in [1, 2, 3]: print a\'

works, but

<         


        
相关标签:
2条回答
  • 2020-12-10 16:03

    Not an answer to your exact question, but still may help someone. You can actually split the command line in shell.

    sh/bash/etc:

    python -c 'import sys
    for a in [1, 2, 3]: print a'
    

    Windows cmd (C:\> and 'More?' are cmd prompts, don't enter those):

    C:\>python -c import sys^
    More?
    More? for a in [1, 2, 3]: print a
    
    0 讨论(0)
  • 2020-12-10 16:04

    You can only use ; to separate non-compound statements on a single line; the grammar makes no allowance for a non-compound statement and a compound statement separated by a semicolon.

    The relevant grammar rules are as follows:

    stmt: simple_stmt | compound_stmt
    simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
    

    The ; in the simple_stmt production is the only place where semicolons are allowed to separate statements. For further details, see the full Python grammar.

    0 讨论(0)
提交回复
热议问题