Just make sure the python executable is in your PATH environment variable then add in your script

python path/to/the/python_script.py

Details:

  • In the file job.sh, put this
#!/bin/sh
python python_script.py
  • Execute this command to make the script runnable for you : chmod u+x job.sh
  • Run it : ./job.sh
Answer from Jean-Bernard Jansen on Stack Overflow
๐ŸŒ
Medium
medium.com โ€บ capital-one-tech โ€บ bashing-the-bash-replacing-shell-scripts-with-python-d8d201bc0989
Bashing the Bash โ€” Replacing Shell Scripts with Python | by Steven F. Lott | Capital One Tech | Medium
February 21, 2020 - Because shell code is so common, Iโ€™ll provide some detailed examples of how to translate legacy shell scripts into Python. Iโ€™ll assume a little familiarity with Python. The examples will be in Python 3.6 and include features like pathlib and f-strings.
Discussions

How can I call a shell script from Python code? - Stack Overflow
How can call/run such example.sh file in python? I need to connect to the oracle cloud then, I should use the script you written here. Could you please write the additional code (how to connect an example.sh file which in in OCI)? Thank you. 2021-03-16T12:56:06.183Z+00:00 ... If your shell script ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Run Python Code in a Shell Script
What kind of uses cases are you looking at where embedding python in a bash scripts is a better approach than calling a separate python file? It might be failure of imagination on my part, but I'm struggling to think of one. I could see some cases where a perl one-liner might work, but perl has nice command line flag (e,p,i) pack a lot of magic into a short command. More on reddit.com
๐ŸŒ r/devops
49
68
February 1, 2021
How to include python script inside a bash script - Unix & Linux Stack Exchange
For newer releases after 5.1 ... of the shell is 50 or lower, or if the size of the here-document is larger than the pipe buffer size of the system, the here-document is saved to a temporary file. ... You can use heredoc if you want to keep the source of both bash and python scripts ... More on unix.stackexchange.com
๐ŸŒ unix.stackexchange.com
February 13, 2015
From Bash to Python
The 2 code review is from a spaghetti bash script that I use a lot, but I canโ€™t show it to you because there are some sensitive commands in there. Before I start to convert it to Python WITHOUT the help of an AI, do you have any suggestions? More on discuss.python.org
๐ŸŒ discuss.python.org
0
1
May 1, 2023
People also ask

Can I execute shell commands directly from Python scripts?
Python modules like os, subprocess, sys, platform, etc. execute shell commands.
๐ŸŒ
simplilearn.com
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ shell scripting in python: a beginner's guide!
Shell Scripting in Python 2024: A Complete Overview!
How does Python compare to traditional shell scripting languages like Bash?
Unix-like systems benefit from bash scripts for file manipulation, system administration, and task automation. Python, a full-featured programming language, simplifies difficult jobs, data manipulation, and cross-platform applications.
๐ŸŒ
simplilearn.com
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ shell scripting in python: a beginner's guide!
Shell Scripting in Python 2024: A Complete Overview!
How can I optimize Python shell scripts for performance?
Dash or ksh is faster and lighter than Bash or zsh, which can improve script performance. Reduce overhead and resource-consuming subprocesses. Instead of pipes or subshells, try built-in commands, process substitution, or command grouping. For large or sophisticated operations, utilize text processing tools like awk, sed, or grep instead of loops. Lastly, arrays or associative arrays can store and access data instead of repeatedly reading or writing files or variables.
๐ŸŒ
simplilearn.com
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ shell scripting in python: a beginner's guide!
Shell Scripting in Python 2024: A Complete Overview!
๐ŸŒ
pytz
pythonhosted.org โ€บ scriptine โ€บ intro.html
Python shell scripting made easy โ€” scriptine 0.2.0 documentation
Make it easy to work with files, directories and other shell commands. To create commands with scriptine, you just create a normal python function for each command of your script and scriptine handles the rest.
๐ŸŒ
Reddit
reddit.com โ€บ r/devops โ€บ run python code in a shell script
r/devops on Reddit: Run Python Code in a Shell Script
February 1, 2021 -

I recently wrote a blog post on how to run Python directly from a shell script. As DevOps professionals, we oftentimes have to mix complexity that is best done in Python, but we don't want to manage or maintain multiple files for the script functionality.

This post shows how you can embed your Python code directly in your shell script. Also it can show some things you need to consider. And finally it explains how to debug that Python code!

Find elsewhere
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
From Bash to Python - Python Help - Discussions on Python.org
May 1, 2023 - The 2 code review is from a spaghetti bash script that I use a lot, but I canโ€™t show it to you because there are some sensitive commands in there. Before I start to convert it to Python WITHOUT the help of an AI, do youโ€ฆ
Top answer
1 of 3
38

Answer

Let's break it down into pieces. Especially the pieces you got wrong. :)


Assignment

outfile=ReadsAgain.txt

It should come to little surprise that you need to put quotes around strings. On the other hand, you have the luxury of putting spaces around the = for readability.

outfilename = "ReadsAgain.txt"

Variable expansion โ†’ str.format (or, the % operation)

python reads.py <snip/> -q$queries <snip/>

So you know how to do the redirection already, but how do you do the variable expansion? You can use the format method (v2.6+):

command = "python reads.py -r1 -pquery1.sql -q{0} -shotelspec -k6 -a5".format(queries)

You can alternatively use the % operator:

#since queries is a number, use %d as a placeholder
command = "python reads.py -r1 -pquery1.sql -q%d -shotelspec -k6 -a5" % queries

C-style loop โ†’ Object-oriented-style loop

for ((r = 1; r < ($runs + 1); r++)) do done

Looping in Python is different from C-style iteration. What happens in Python is you iterate over an iterable object, like for example a list. Here, you are trying to do something runs times, so you would do this:

for r in range(runs):
  #loop body here

range(runs) is equivalent to [0,1,...,runs-1], a list of runs = 5 integer elements. So you'll be repeating the body runs times. At every cicle, r is assigned the next item of the list. This is thus completely equivalent to what you are doing in Bash.

If you're feeling daring, use xrange instead. It's completely equivalent but uses more advanced language features (so it is harder to explain in layman's terms) but consumes less resources.


Output redirection โ†’ the subprocess module

The "tougher" part, if you will: executing a program and getting its output. Google to the rescue! Obviously, the top hit is a stackoverflow question: this one. You can hide all the complexity behind it with a simple function:

import subprocess, shlex
def get_output_of(command):
  args = shlex.split(command)
  return subprocess.Popen(args,
                          stdout=subprocess.PIPE).communicate()[0]
  # this only returns stdout

So:

python reads.py -r1 -pquery1.sql -q$queries -shotelspec -k6 -a5 >> $outfile

becomes:

command = "python reads.py -r1 -pquery1.sql -q%s -shotelspec -k6 -a5" % queries
read_result = get_output_of(command)

Don't over-subprocess, batteries are included

Optionally, consider that you can get pretty much the same output of date with the following:

import time
time_now = time.strftime("%c", time.localtime()) # Sat May 15 15:42:47 2010

(Note the absence of the time zone information. This should be the subject of another question, if it is important to you.)


How your program should look like

The final result should then look like this:

import subprocess, shlex, time
def get_output_of(command):
  #... body of get_output_of
#... more functions ...
if __name__ = "__main__":
  #only execute the following if you are calling this .py file directly,
  #and not, say, importing it
  #... initialization ...
  with file("outputfile.txt", "a") as output_file: #alternative way to open files, v2.5+
    #... write date and other stuff ...
    for r in range(runs):
      #... loop body here ...

Post scriptum

That must look pretty horrible when compared to the relatively simple and short Bash script, right? Python is not a specialized language: it aims to do everything reasonably well, but isn't built directly for running programs and getting the output of those.

Still, you wouldn't normally write a database engine in Bash, right? It's different tools for different jobs. Here, unless you're planning to make some changes that would be non-trivial to write with that language, [Ba]sh was definitely the right choice.

2 of 3
11

It should be fairly simple to port your program. The only tricky part will be running the db2 command and (maybe) refactoring reads.py so that it can be called as a library function.

The basic idea is the same:

  • Setting local variables is the same.
  • Replace echo with print.
  • Replace your loop with for r in range(runs):.
  • Get the date with the datetime module.
  • Replace write to file with the file objects module.
  • Replace the call to db2 with the subprocess module.
  • You'll need to import reads.py to use as a library (or you can use subprocess).

But, as Marcelo says, if you want more help- you're best off putting in some effort of your own to ask direct questions.

๐ŸŒ
Simplilearn
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ shell scripting in python: a beginner's guide!
Shell Scripting in Python 2024: A Complete Overview!
July 31, 2025 - Learn the basics of shell scripting in Python. This guide covers Python assignment operators and how to use them for effective shell scripting in Python.
Address ย  5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
๐ŸŒ
GitHub
github.com โ€บ lamerman โ€บ shellpy
GitHub - lamerman/shellpy: A tool for convenient shell scripting in python ยท GitHub
It allows you to write all your shell scripts in Python in a convenient way and in many cases replace Bash/Sh.
Starred by 639 users
Forked by 61 users
Languages ย  Python 98.7% | Smarty 1.3%
๐ŸŒ
Thomas Stringer
trstringer.com โ€บ python-in-shell-script
Run Python Code in a Shell Script | Thomas Stringer
January 31, 2021 - Butโ€ฆ sometimes it is also convenient ... Put your Python directly in your shell scripts! How can you do this? Construct your multiline Python string and then pass the ad hoc Python code in with the -c parameter....
๐ŸŒ
Adam Young's Web Log
adam.younglogic.com โ€บ 2025 โ€บ 02 โ€บ converting-a-shell-script-to-python
Converting a Shell Script to Python | Adam Young's Web Log
February 12, 2025 - However, if I want to capture the output from that command and append it to the console, it gets more complex. Add in the need for pipes and other bash-isms and you end up writing a bit of boilerplate code for each invocation. Other people have gone through this and come up with wrappers that make it simpler. Ricardo, A fellow Python-Over-Coffee participant, suggested i take a look at the plumbum library. It has been a great starting point. With it, I can line-for-line convert the majority of the shell scripts to python.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-9102.html
embedding Python script in shell scripts
i'm starting to think through how to embed a Python script inside a shell script. the first issue that comes to mind is keep the data input and code input separate. i don't want to write the code to a separate file because it may be that there is n...
๐ŸŒ
LinuxConfig
linuxconfig.org โ€บ home โ€บ how to use a bash script to run your python scripts
How to Use a Bash Script to Run Your Python Scripts
September 21, 2025 - ... To run a Python script from a bash script, we should first change to the directory containing the Python script using the cd command, and then use the python command to execute the script.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ scripting โ€บ how to call python from a bash script
How to Call Python From a Bash Script | Baeldung on Linux
March 18, 2024 - By calling Python scripts from within Bash, we can perform a wider range of complex tasks and automate workflows efficiently. In this tutorial, weโ€™ll explore how to call the Python interpreter from a Bash script and how to embed Python code within Bash.
๐ŸŒ
Python Course
python-course.eu โ€บ applications-python โ€บ python-and-the-shell.php
2. Python and the Shell | Applications | python-course.eu
It's not possible in Python to read a character without having to type the return key as well. On the other hand this is very easy on the Bash shell. The Bash command read -n 1 waits for a key (any key) to be typed. If you import os, it's easy to write a script providing getch() by using os.system() and the Bash shell.
๐ŸŒ
Codementor
codementor.io โ€บ community โ€บ using bash and python together (with samples)
Using Bash and Python Together (With Samples) | Codementor
September 11, 2023 - You can pass command-line arguments to your Python script from Bash. These arguments can be used to customize the behavior of your script. In Python, you can access these arguments using the sys.argv list from the sys module.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-run-bash-script-in-python
How to run bash script in Python? - GeeksforGeeks
September 13, 2022 - As an argument, you have to pass the command you want to invoke and its arguments, all wrapped in a list. ... A new process is created, and command echo is invoked with the argument "Geeks for geeks". Although, the command's result is not captured by the python script.
๐ŸŒ
The xonsh shell
xon.sh
The Xonsh Shell โ€” Python-powered shell. Python shell. Python in the shell. Shell in Python. Shell and Python. Python and shell.
Read more โ†’ ยท cd $HOME id $(whoami) > ~/id.txt cat /etc/passwd | grep root $PROMPT = '@ ' The xonsh language is a superset of Python 3, allowing you to execute Python code directly, install and use third-party libraries, import modules, and ...