Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

embedding short python scripts inside a bash script

Tags:

python

bash

I'd like to embed the text of short python scripts inside of a bash script, for use in say, my .bash_profile. What's the best way to go about doing such a thing?

The solution I have so far is to call the python interpreter with the -c option, and tell the interpreter to exec whatever it reads from stdin. From there, I can build simple tools like the following, allowing me to process text for use in my interactive prompt:

function pyexec() {     echo "$(/usr/bin/python -c 'import sys; exec sys.stdin.read()')" }  function traildirs() {     pyexec <<END trail=int('${1:-3}') import os home = os.path.abspath(os.environ['HOME']) cwd = os.environ['PWD'] if cwd.startswith(home):     cwd = cwd.replace(home, '~', 1) parts = cwd.split('/') joined = os.path.join(*parts[-trail:]) if len(parts) <= trail and not joined.startswith('~'):     joined = '/'+joined print joined END }  export PS1="\h [\$(traildirs 2)] % " 

This approach smells slightly funny to me though, and I'm wondering what alternatives to doing it this way might be.

My bash scripting skills are pretty rudimentary, so I'm particularly interested to hear if I'm doing something silly from the bash interpreter's perspective.

like image 610
Matt Anderson Avatar asked Feb 03 '10 01:02

Matt Anderson


People also ask

Can you run a Python script in a Bash script?

We can make use of the bash script to run the Python script in macOS/Ubuntu. Both these operating systems support bash scripts. Let's see the steps to run Python scripts using a bash script. Open any text editor.

Can we write Python code in shell script?

Instead of writing the entire python code in shell script, you can embed python code inside the bash shell script using here doc. First lets write a working python code. To demonstrate, let me write a small piece of Python code that just simply gets the file properties of a given file name.


1 Answers

Why should you need to use -c? This works for me:

python << END ... code ... END 

without needing anything extra.

like image 132
Ricardo Cárdenes Avatar answered Oct 01 '22 08:10

Ricardo Cárdenes