Python Forum
embedding Python script in shell scripts
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
embedding Python script in shell scripts
#3
You can do this with here-doc.

#!/bin/bash

echo "Hello World from bash"

python <<EOF
from __future__ import print_function
import sys
print(sys.version)
print("Using a variable from shell: $PWD")
EOF

python <<'EOF'
from __future__ import print_function
print('Without variables: $PWD')
EOF

echo "Preparing a list in shell"
li=(1 2 3 4 5 6)
echo ${li[@]}

python <<EOF
from __future__ import print_function
print('Using list from shell in Pyhon')
numbers = list(map(int, "${li[@]}".split()))
print(numbers)
EOF

if [ -x '/usr/bin/python3' ]; then
/usr/bin/python3 <<EOF
import sys
print('Python 3 exists on this system....')
print(sys.version)
EOF
fi


if [ -x '/usr/bin/python3' ]; then
        PYTHON='/usr/bin/python3'
elif [ -x '/usr/bin/python2' ]; then
        PYTHON='/usr/bin/python2'
elif [ -x '/usr/bin/python' ]; then
        PYTHON='/usr/bin/python'
fi

$PYTHON <<'EOF'
from __future__ import print_function
import sys
print('Using detected Python interpreter...')
print(sys.version)
EOF
Output:
Hello World from bash 2.7.14 (default, Sep 23 2017, 22:06:14) [GCC 7.2.0] Using a variable from shell: /home/andre Without variables: $PWD Preparing a list in shell 1 2 3 4 5 6 Using list from shell in Pyhon [1, 2, 3, 4, 5, 6] Python 3 exists on this system.... 3.6.3 (default, Oct 3 2017, 21:45:48) [GCC 7.2.0] Using detected Python interpreter... 3.6.3 (default, Oct 3 2017, 21:45:48) [GCC 7.2.0]
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: embedding Python script in shell scripts - by DeaD_EyE - Mar-21-2018, 09:45 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  embedded Python scripts - is it worthwhile Skaperen 3 791 Feb-21-2024, 01:25 AM
Last Post: Skaperen
  images and pixels in typical Python scripts Skaperen 0 1,271 Oct-14-2021, 12:29 AM
Last Post: Skaperen
  embedding data in a script Skaperen 1 2,125 May-31-2021, 07:19 AM
Last Post: Gribouillis
  Creating Python scripts in Visual Studio Code Sanjish 4 2,661 Dec-22-2020, 12:32 PM
Last Post: snippsat
  embedding python Skaperen 0 1,492 Apr-22-2020, 03:19 AM
Last Post: Skaperen
  suid scripts in python? Skaperen 0 2,184 Sep-29-2019, 10:28 PM
Last Post: Skaperen
  Python Shell As Preferred Mode For Integrated Terminal In Visual Studio Code adt 4 4,113 Sep-07-2019, 06:00 PM
Last Post: adt
  Can copyright be applied python scripts? tim777 3 4,957 Sep-04-2019, 12:20 PM
Last Post: DeaD_EyE
  Finding Scripts for Python Johnny1998 1 2,249 Jul-31-2019, 08:07 PM
Last Post: Yoriz
  Notepad vs anaconda spyder or python shell ShadowAlpha 2 2,973 Jun-26-2019, 06:31 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020