Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mix bash with python

Tags:

python

bash

I enjoy using unix commands very much, but I came to the point, where I would find embedded python parts useful. This is my code:

#!/bin/bash -
echo "hello!";

exec python <<END_OF_PYTHON
#!/usr/bin/env python

import sys

print ("xyzzy")

sys.exit(0)
END_OF_PYTHON

echo "goodbye!";

However, only "hello" gets printed.

$ ./script.sh 
hello!
xyzzy

How can I modify the bash script to fully embedd python? And would it then be possible to pass values from python variables into bash variables? Thanks a lot.

like image 557
Perlnika Avatar asked Mar 05 '14 16:03

Perlnika


People also ask

Can you combine bash and Python?

Others have answered your specific issue, but in answer to the general question "How to mix bash with python", Xonsh may be useful to you. It's a special shell that allows you to use python and bash side-by-side. There's also sultan if you want to be able to easily call bash from python.

Can you run a bash script in Python?

Is there any way to execute the bash commands and scripts in Python? Yeah, Python has a built-in module called subprocess which is used to execute the commands and scripts inside Python scripts.

Can I replace bash with Python?

According to the accepted answer for this SO question: , Python can make a great bash replacement.


2 Answers

On the exec python ... line, you're exec()ing the Python interpreter on your PATH, so the python image will replace the bash image, and there is absolutely no hope of the echo "goodbye!" ever being executed. If that's what you want, that's fine, but otherwise, just omit the exec.

The shebang (“#!”) line in the python code is completely unnecessary. When you try to run an ordinary file, the kernel sees the “#!”, runs whatever follows it (/usr/bin/env python), and feeds the rest of the file to the stdin of whatever has been run. This is a general facility used to invoke interpreters. Since you are invoking the python interpreter yourself, not asking the kernel to do it, this is neither needed nor useful.

The sys.exit(0) is also unnecessary, since the Python interpreter will naturally exit when it gets to the end of its input (at END_OF_PYTHON) anyway. This means that the import sys is also unnecessary.

In summary, the following is what I would write to achieve what you appear to want to achieve:

#!/bin/bash
echo "hello!";

python <<END_OF_PYTHON
print ("xyzzy")
END_OF_PYTHON

echo "goodbye!";
like image 112
Emmet Avatar answered Sep 27 '22 21:09

Emmet


Don't use exec. That replaces the shell process with the program you're running, so the rest of the script doesn't execute.

#!/bin/bash -
echo "hello!";

python <<END_OF_PYTHON
#!/usr/bin/env python

import sys

print ("xyzzy")

sys.exit(0)
END_OF_PYTHON

echo "goodbye!";
like image 25
Barmar Avatar answered Sep 27 '22 21:09

Barmar