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.

Answer from badp on Stack Overflow
🌐
GitHub
github.com › clarity20 › bash2py
GitHub - clarity20/bash2py: The only Bash-to-python transpiler you will ever need! https://www.swag.uwaterloo.ca/bash2py/index.html
This is an adaptation of bash's expr.c. Instead of performing computations, we reformat bash arithmetic expressions into equivalent Python expressions. (Changed & added) burp.c, dynamo.c These files implement the buffering, logging and code generation subsystems for the transpiler. The bash source code comes from bash-4.3.30 but a forward port is on the agenda. Please reach out to the project maintainer via this online repository.
Starred by 38 users
Forked by 17 users
Languages   C 68.7% | HTML 15.9% | Yacc 6.6% | Shell 3.1% | Perl 2.6% | Makefile 2.1% | C 68.7% | HTML 15.9% | Yacc 6.6% | Shell 3.1% | Perl 2.6% | Makefile 2.1%
🌐
GitHub
github.com › syuanca › bash2python
GitHub - syuanca/bash2python: A tool that converts a bash script to python script
A tool that converts a bash script to python script - syuanca/bash2python
Starred by 22 users
Forked by 11 users
Languages   Python 56.7% | Shell 43.3% | Python 56.7% | Shell 43.3%
Discussions

Automatically converting (most of?) n bash scripts to Python?
Hello people. I’ve been writing a bunch of scripts, sometimes in bash, sometimes in Python, to automate the mundane parts of my job. My management has decided they don’t want the bash anymore, so I’ve been asked to move in the direction of Python. That’s kind of cool, really. More on discuss.python.org
🌐 discuss.python.org
0
0
June 21, 2024
Converting a bash script to python (small script) - Stack Overflow
I’ve a bash script I’ve been using for a Linux environment but now I have to use it on a Windows platform and want to convert the bash script to a python script which I can run. The bash script is More on stackoverflow.com
🌐 stackoverflow.com
Converting the complete environment from Bash to Python because of portability
I wanted to ask if there are any plans to remove the bash completely from the project? In the presentation for the release of the project as open source, there was still talk of the need to switch ... More on github.com
🌐 github.com
6
February 2, 2018
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
🌐
GitHub
github.com › AlanCoding › tower-cli-bash-to-python-converter
GitHub - AlanCoding/tower-cli-bash-to-python-converter: tries to convert tower-cli bash commands into python
tries to convert tower-cli bash commands into python - AlanCoding/tower-cli-bash-to-python-converter
Starred by 3 users
Forked by 4 users
Languages   Shell 54.7% | Python 45.3% | Shell 54.7% | Python 45.3%
🌐
Python.org
discuss.python.org › python help
Automatically converting (most of?) n bash scripts to Python? - Python Help - Discussions on Python.org
June 21, 2024 - Hello people. I’ve been writing a bunch of scripts, sometimes in bash, sometimes in Python, to automate the mundane parts of my job. My management has decided they don’t want the bash anymore, so I’ve been asked to mov…
🌐
GitHub
gist.github.com › 1583330
Convert shell script variables to python · GitHub
August 10, 2016 - Convert shell script variables to python. GitHub Gist: instantly share code, notes, and snippets.
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.

🌐
grep Flags
zwischenzugs.com › 2016 › 08 › 29 › bash-to-python-converter
Bash to Python Converter – zwischenzugs.com
August 29, 2016 - Generally I start with a bash script because it’s so fast to get going, but as time goes on I add features, and then wish I had started it in python so that I could access all the modules and functionality that’s harder to get to in bash. I found a bash2py tool, which looked good, but came as a zipped source download (not even in a git repo!). I created a Docker image to convert it, and have used it a couple of times.
Find elsewhere
🌐
CodingFleet
codingfleet.com › code-converter › bash › python
Bash to Python Converter - CodingFleet
Convert your Bash Code to Python. This exceptional AI-powered tool converts your Bash code into Python code easily, eliminating the need for manual re-coding. Save your precious time and unlock cross-platform development like never before with our converter tool.
🌐
GitHub
github.com › avast › retdec › issues › 147
Converting the complete environment from Bash to Python because of portability · Issue #147 · avast/retdec
February 2, 2018 - In my opinion, however, it would be quite desirable if Python could be used to depict the whole thing. This way you wouldn't have to do such a headstand under Windows to get the system up and running. The best way to do this is to simply run the program without external dependencies.
Author   0xBEEEF
🌐
GitHub
github.com › ninjaaron › replacing-bash-scripting-with-python
GitHub - ninjaaron/replacing-bash-scripting-with-python: Guide on using using python for administrative scripting · GitHub
Using stdin, stdout and stderr, you can write python programs which behave as filters and integrate well into a Unix workflow. Arguments are passed to your program as a list which you can access using sys.argv. This is a bit like $@ in Bash, or $1 $2 $3...
Starred by 1.1K users
Forked by 112 users
🌐
ResearchGate
researchgate.net › publication › 295302947_Bash2py_A_bash_to_Python_translator
Bash2py: A bash to Python translator | Request PDF
March 1, 2015 - Bash also suffers from poor performance, memory leakage problems, and limited functionality which make continued dependence on it problematic. At the request of our industrial partner, we therefore developed a source-to-source translator, bash2py, ...
🌐
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…
🌐
Medium
medium.com › zwischenzugs › bash-to-python-converter-c58580f26f6c
Bash to Python Converter | by Ian Miell | zwischenzugs | Medium
October 9, 2016 - #!/bin/bash if [ $# -lt 1 ] then echo "Usage: $0 file ..." exit 1 fiecho "$0 counts the lines of code"l=0for f in $* do l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'` echo "$f: $l" doneHere's a conversion session:imiell@Ians-Air:/space/git/work/bin$ docker run -ti imiell/bash2py Unable to find image 'imiell/bash2py:latest' locally latest: Pulling from imiell/bash2py 357ea8c3d80b: Already exists 98b473a7fa6a: Pull complete a7f8553161b4: Pull complete a1dc4858a149: Pull complete 752a5d408084: Pull complete cf7fa7bc103f: Pull complete Digest: sha256:110450838816d2838267c394bcc99ae00c99f8162fa85a1daa01
🌐
Linux Questions
linuxquestions.org › questions › linux-software-2 › need-help-converting-bash-script-to-python-4175605267
Need help converting BASH script to Python
Ive been tasked to convert a bash script to python. So far, the only way I know how to do that is to wrap every statement in the bash script with a
Top answer
1 of 2
3
import os

for i in range(1, 50):
    env_var = os.environ[f'{i}nl']
    os.system(f"ssh BF-c{env_var} 'hostname; free -h; uname -a;'")

Python3.6 >

    env_var = os.environ[str(i) + 'nl']
    os.system("ssh BF-c{} 'hostname; free -h; uname -a;'".format(env_var))
2 of 2
2

You can do it using Bash2Py.

Also, you can try using the docker image

Courtesy: Bash to Python

So the below code is actually the complete script for conversion.

#! /usr/bin/env python
from __future__ import print_function

import sys,os

class Bash2Py(object):
  __slots__ = ["val"]
  def __init__(self, value=''):
    self.val = value
  def setValue(self, value=None):
    self.val = value
    return value

def GetVariable(name, local=locals()):
  if name in local:
    return local[name]
  if name in globals():
    return globals()[name]
  return None

def Make(name, local=locals()):
  ret = GetVariable(name, local)
  if ret is None:
    ret = Bash2Py(0)
    globals()[name] = ret
  return ret

def Array(value):
  if isinstance(value, list):
    return value
  if isinstance(value, basestring):
    return value.strip().split(' ')
  return [ value ]

class Expand(object):
  @staticmethod
  def at():
    if (len(sys.argv) < 2):
      return []
    return  sys.argv[1:]
  @staticmethod
  def star(in_quotes):
    if (in_quotes):
      if (len(sys.argv) < 2):
        return ""
      return " ".join(sys.argv[1:])
    return Expand.at()
  @staticmethod

  def hash():
    return  len(sys.argv)-1

if (Expand.hash() < 1 ):
    print("Usage: "+__file__+" file ...")
    exit(1)

print(__file__+" counts the lines of code")

l=Bash2Py(0)

for Make("f").val in Expand.star(0):
    Make("l").setValue(os.popen("wc -l "+str(f.val)+" | sed \"s/^\\([0-9]*\\).*$/\\1/\"").read().rstrip("\n"))
    print(str(f.val)+": "+str(l.val))

The guts of the code is in the for loop at the bottom.

bash2py does some safe conversion and wrapping of the bash script into some methods such as ‘Make’, ‘Array’ et al that we can get rid of with a little work.

By replacing:

  • Bash2Py(0) with 0
  • Make(“f”).val with f and Make(“l”) with l etc
  • f.val with f and l.val with l etc
🌐
Stack Exchange
unix.stackexchange.com › questions › 627842 › problem-when-converting-bash-to-python-using-bash2py
shell script - Problem when converting bash to python using bash2py - Unix & Linux Stack Exchange
January 6, 2021 - Thanks to Pradeep's tip, I was able to isolate this by comparing the source for version 3.6 and 2.3. See the following Github issue for details: https://github.com/clarity20/bash2py/issues/5. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Community Asks Sprint Announcement – January 2026: Custom site-specific badges! 21 How to include python script inside a bash script
🌐
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 - I’ll assume a little familiarity with Python. The examples will be in Python 3.6 and include features like pathlib and f-strings. If you want to follow along, consider creating a virtual environment or using conda. The shell script examples are pure bash, and will run anywhere that bash runs.