Embedding Python in a shell script

J

Jason Friedman

$ 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?
 
H

Hans Mulder

you can use a here document like this:


#! /bin/bash

/usr/bin/python2<< EOPYTHON
def hello():
print("Hello, World");

if __name__ == "__main__":
hello();

EOPYTHON

That does not solve the problem as stated. The OP wants to call python
inside a loop and he wants to indent things properly:

#!/bin/bash

for i in 1 2 3 4 5
do
python << EOPYTHON
def hello():
print("Hello, World");

if __name__ == "__main__":
hello();
EOPYTHON
done

That doesn't work, because the EOPYTHON token is indented.

If you put the EOPYTHON token flush left, it still doesn't work, because
Python does not accept indentation on line 1:

File "<stdin>", line 1
def hello():
^
IndentationError: unexpected indent


For some ideas that may work, read the earlier posts in this thread.


-- HansM
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top