Python command line argument semicolon-loop error

后端 未结 4 2047
猫巷女王i
猫巷女王i 2020-12-10 17:56

I was trying out python -mtimeitso I put python -mtimeit \"n = 0; while n < 10: pass\" Then an invalid syntax error showed up. same with semicol

相关标签:
4条回答
  • 2020-12-10 18:18

    timeit can take two parameters: the setup code and the code to time.

    python -mtimeit "n = 0" "while n < 10: pass"
    

    Also, you should change that pass to n += 1 or you'll be in an infinite loop.

    0 讨论(0)
  • 2020-12-10 18:22

    The selected answer superbly tackles the why, but not the question of how this can be worked around under any operating system (since windows cmd doesn't allow multi-line statements)

    The answer is: exec

    You have to nest any loops in an exec statement.

    Examples: (Python 2)

    python -c "i = 3; while i:print i; i-=1"
    

    is a syntax error, while

    python -c "i = 3; exec 'while i:print i;i-=1'"
    

    works correctly.

    0 讨论(0)
  • 2020-12-10 18:39

    If you're writing it in a script, why don't you indent it just the way you would do it in a real python program? Like this:

    python -mtimeit "
    n = 0
    while n < 10:
        pass"
    
    0 讨论(0)
  • 2020-12-10 18:41

    while, for can't have semicolon before, they need to be on one line. If you looked at Python grammar:

    compound_stmt ::=  if_stmt
                       | while_stmt
                       | for_stmt
                       | try_stmt
                       | with_stmt
                       | funcdef
                       | classdef
                       | decorated
    suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
    statement     ::=  stmt_list NEWLINE | compound_stmt
    stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]
    

    you will see that the statements that are part of compound_stmt need to be one one line alone. The only statements that can be separated by semicolon are simple_stmt group:

    simple_stmt ::=  expression_stmt
                     | assert_stmt
                     | assignment_stmt
                     | augmented_assignment_stmt
                     | pass_stmt
                     | del_stmt
                     | print_stmt
                     | return_stmt
                     | yield_stmt
                     | raise_stmt
                     | break_stmt
                     | continue_stmt
                     | import_stmt
                     | global_stmt
                     | exec_stmt
    
    0 讨论(0)
提交回复
热议问题