Embedding Python in a shell script

Jason Friedman jason at powerpull.net
Thu Jun 16 20:57:25 EDT 2011


$ cat test.sh
#!/bin/bash
for i in 1 2 3 4; do
   python -c "
for j in range($i):
   print j
"
done

$ sh test.sh
0
0
1
0
1
2
0
1
2
3

The code behaves as I expect and want, but the de-denting of the
Python call is unattractive, especially unattractive the longer the
Python call becomes.  I'd prefer something like:

$ cat test.sh
#!/bin/bash
for i in 1 2 3 4; do
   python -c "
       for j in range($i):
           print j
   "
done

But that yields:

$ sh test.sh
 File "<string>", line 2
   for j in range(1):
   ^
IndentationError: unexpected indent
 File "<string>", line 2
   for j in range(2):
   ^
IndentationError: unexpected indent
 File "<string>", line 2
   for j in range(3):
   ^
IndentationError: unexpected indent
 File "<string>", line 2
   for j in range(4):
   ^
IndentationError: unexpected indent

I realize I can create a "call_me.py" and do:

$ cat test.sh
#!/bin/bash
for i in 1 2 3 4; do
   python call_me.py $i
done

but for various reasons I want a single script.  Any alternatives?



More information about the Python-list mailing list