Mixed shell and python script possible?

I swear I saw this before, but cannot find it now. Is it possible to have a shell script run the python interpreter "middle thread", that is:

#!/bin/bash #shell stuff.. set +e VAR=aabb for i in abc; 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) 
+6
source share
6 answers

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

 #!/bin/sh echo this is a shell script python <<@@ print 'hello from Python!' @@ 

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

+8
source

You can write

 exec python <<END_OF_PYTHON #!/usr/bin/env python import sys print ("xyzzy") sys.exit(0) END_OF_PYTHON 

to replace the Bash process with Python and pass the specified Python program to its standard input. ( exec replaces the Bash process. <<END_OF_PYTHON forces standard input to contain everything up to END_OF_PYTHON .)

+2
source

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

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

or

 python -c ' import sys print("xyzzy") sys.exit(0) ' 
+2
source

Of course, right after I posted this, I remembered a way to do this:

 #!/bin/sh echo Shell python <<EOF import sys print "Python" sys.exit(0) EOF 
0
source

I agree that blending / mashing can be a pretty powerful method - not only in scripts, but also on the command line (for example, perl interfaces have been very successful over time). So, my little advice on another one-line option (in addition to the mentioned kev) for mixed scripts in bash / python:

 for VAR in $(echo 'import sys; print "xyz"; sys.exit(0)' | python -);do echo "$VAR"; done; 

produces

 x y z 
0
source

This is great for a short inline script / code. If you can rely on a bash script as a suitable glue to write a large, good application, it can have different team members who write code / script in any language that they are good at, and then you can simply relate their work as follows way. Of course, one would also have to assume that there are so many different modes of operation for one application. @ user318904 @phs @piokuc

 #!/bin/bash java hello #hello class bytecode to be in the path python hello.py elixir simple.exs perl hello.pl nodejs sum1.js coffee sum2.coffee #any other bash script can be put anywhere 
0
source

Source: https://habr.com/ru/post/910039/


All Articles