Long programs using python -c switch

后端 未结 4 1288
执笔经年
执笔经年 2021-01-06 09:46

I would like to use python for things I\'ve been doing using bash. Is it possible to use the -c switch for long programs, e.g. a for loop with two statements? This would let

相关标签:
4条回答
  • 2021-01-06 09:53

    If you are running from a bash script, just use quotes:

    #!/bin/sh
    
    python -c 'import os
    for i in range(3):
        for j in range(3):
            print i*j
    '
    
    echo "done"
    

    Otherwise, if using the cmd line, use ; semicolons to seperate statements, or use single quotes again to wrap around to the next line:

    python -c 'import os
    >    for i in range(3):
    >        for j in range(3):
    >            print i*j
    >    '
    
    0 讨论(0)
  • 2021-01-06 09:54

    When used inside a script, I think it would be better to have python read the script from standard input, like so:

    #!/bin/bash
    
    python - arg1 arg2 <<END
    import sys
    print 'Arg:', sys.argv[1:]
    END
    

    This uses bash's HEREDOC syntax.

    0 讨论(0)
  • 2021-01-06 09:55

    You can use compound statements, using the semi-colon to delimiter the statements, such as

    python -c "for x in range(0,3) : print x; print x
    

    Then output would then be:

    0
    0
    1
    1
    2
    2
    

    see http://docs.python.org/reference/compound_stmts.html

    0 讨论(0)
  • 2021-01-06 10:00

    No problem if your underlying shell is bash, since you can continue an argument across multiple lines if an opened ' (quote) is not yet closed -- e.g.:

    $ python -c'for x in range(3):
    >   if x!=1:
    >     print x'
    0
    2
    $
    

    The > is bash's default PS2, the "multi-line continuation prompt", as distinguished from $, AKA PS1, the normal "start entering a command" prompt.

    If you can't use such multi-line continuation, multiple nested block statements (such as an if within a loop) could otherwise be problematic.

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