Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long programs using python -c switch

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 me use python directly from command line, just like bash or php.

Thanks.

EDIT: Don't know how I missed it, simply doing a python -c ' and then pressing enter does what I've wanted to do. I'd tried a lot of variations, and one using a \ but that didn't work, so I asked the question. e.g.

$python -c '
>print "x"
>for i in range(3):
>   print "y" '

does what I wanted to do, though Rod's answer looks good too.

like image 358
0fnt Avatar asked Sep 03 '10 15:09

0fnt


2 Answers

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.

like image 140
Alex Martelli Avatar answered Oct 20 '22 01:10

Alex Martelli


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

like image 24
Rod Avatar answered Oct 20 '22 00:10

Rod