Embedding Python in a shell script

mg marco.giusti at gmail.com
Fri Jun 17 04:58:37 EDT 2011


rusi <rustompmody at gmail.com> wrote:
> On Jun 17, 6:05 am, Chris Angelico <ros... at gmail.com> wrote:
> 
>> > Python call becomes.  I'd prefer something like:
>>
>> #!/bin/bash
>> for i in 1 2 3 4; do
>>   python -c "if True:
> # comfortably indented python code
> 
> Thanks. Nice!

You can use bash here document feature, <<-, that strips heading tab
characters but not spaces.


	#!/bin/bash

	for i in 1 2 3 4; do
		python /dev/stdin <<-EOF
			for i in range($i):
			    print i # two tabs and four spaces
			EOF
	done

Or alternatively you can use a temporary file:


	#!/bin/bash

	TEMPFILE=$(mktemp)
	trap 'rm -f $TEMPFILE' TERM INT

	cat > $TEMPFILE <<EOF
	import sys

	for i in range(int(sys.argv[1])):
	    print i
	EOF

	for i in 1 2 3 4; do
		python $TEMPFILE $i
	done





More information about the Python-list mailing list