Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixed shell and python script possible?

I swear I have seen this done before but can not find it now. Is it possible to have a shell script start a python interpeter "mid stream", ie:

#!/bin/bash
#shell stuff..

set +e

VAR=aabb

for i in a b c; do
    echo $i
done

# same file!

#!/usr/bin/env python
# python would be given this fd which has been seek'd to this point

import sys

print ("xyzzy")

sys.exit(0)
like image 625
user318904 Avatar asked Mar 05 '12 23:03

user318904


2 Answers

You can use this shell syntax (it is called here document in Unix literature):

#!/bin/sh
echo this is a shell script

python <<@@
print 'hello from Python!'
@@

The marker after '<<' operator can by an arbitrary identifier, people often use something like EOF (end of file) or EOD (end of document). If the marker starts a line then the shell interprets it as end of input for the program.

like image 140
piokuc Avatar answered Oct 02 '22 07:10

piokuc


If your python script is very short. You can pass it as a string to python using the -c option:

python -c 'import sys; print "xyzzy"; sys.exit(0)'

Or

python -c '
import sys
print("xyzzy")
sys.exit(0)
'
like image 24
kev Avatar answered Oct 02 '22 08:10

kev