There are 2 ways to solve your problem:

  1. Convert the python script to bash step-by-step (I doubt there is an automated process to do that).
  2. Use PyInstaller to create a binary executable for Linux.
Answer from M. Dm. on askubuntu.com
๐ŸŒ
CodingFleet
codingfleet.com โ€บ code-converter โ€บ python โ€บ bash
Python to Bash Converter - CodingFleet
Convert your Python Code to Bash. This exceptional AI-powered tool converts your Python code into Bash 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 โ€บ clarity20 โ€บ bash2py
GitHub - clarity20/bash2py: The only Bash-to-python transpiler you will ever need! https://www.swag.uwaterloo.ca/bash2py/index.html
Welcome to the new home of bash2py, a software tool that translates Bash shell code into Python.
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%
Discussions

bash - How to convert this Python script to a shell script? - Stack Overflow
I need code that is exactly like this but for Bash. ... Kyle G. โ€“ Kyle G. 2013-08-19 19:23:10 +00:00 Commented Aug 19, 2013 at 19:23 ... How is python code not a Linux executable script? It runs on Linux and if you set execute permissions, it's executable. ... Sign up to request clarification ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Help Request - convert python code to bash script
So what have you tried so far? More on reddit.com
๐ŸŒ r/bash
4
0
April 2, 2022
shell script - Python to Bash Conversion? - Unix & Linux Stack Exchange
Problem: I came across a python program that was able to scan your network and tell you the hosts that are connected to it and / or kick unwanted users off your own network. It works well, but I'm... More on unix.stackexchange.com
๐ŸŒ unix.stackexchange.com
July 10, 2017
Is it possible to convert bash scripts into Python scripts?
Yes. Python can run shell commands as well, but a lot of things just have straight Python equivalents. More on reddit.com
๐ŸŒ r/learnpython
8
2
May 11, 2024
People also ask

Can I convert entire projects or just single files?
You can convert both single files and entire projects. For large projects, our tool maintains the directory structure and handles dependencies between files. We also provide batch processing for converting multiple files at once.
๐ŸŒ
devrevive.com
devrevive.com โ€บ convert โ€บ python-to-bash
Python to Bash Converter | DevRevive
How does the code conversion work?
Our code conversion tool uses advanced machine learning models trained on millions of code examples. It analyzes your source code, identifies patterns, and generates equivalent code in the target language. The process is fully automated, but you can review and tweak the output before finalizing the conversion.
๐ŸŒ
devrevive.com
devrevive.com โ€บ convert โ€บ python-to-bash
Python to Bash Converter | DevRevive
Which programming languages are supported?
DevSurvive supports over 50 programming languages, including Python, TypeScript, JavaScript, Java, C#, Ruby, Go, Rust, PHP, and more. You can convert code between any two supported languages with just a few clicks.
๐ŸŒ
devrevive.com
devrevive.com โ€บ convert โ€บ python-to-bash
Python to Bash Converter | DevRevive
๐ŸŒ
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%
๐ŸŒ
Reddit
reddit.com โ€บ r/bash โ€บ help request - convert python code to bash script
r/bash on Reddit: Help Request - convert python code to bash script
April 2, 2022 -

Apologies if this is the wrong subreddit to post this. I found a script to manipulate timecodes for FFMPEG metadata and am hoping someone would help me convert the code to a bash script.

Here's the python code:

import re

chapters = list()

with open('chapters.txt', 'r') as f:
   for line in f:
      x = re.match(r"(\d):(\d{2}):(\d{2}) (.*)", line)
      hrs = int(x.group(1))
      mins = int(x.group(2))
      secs = int(x.group(3))
      title = x.group(4)

      minutes = (hrs * 60) + mins
      seconds = secs + (minutes * 60)
      timestamp = (seconds * 1000)
      chap = {
         "title": title,
         "startTime": timestamp
      }
      chapters.append(chap)

text = ""

for i in range(len(chapters)-1):
   chap = chapters[i]
   title = chap['title']
   start = chap['startTime']
   end = chapters[i+1]['startTime']-1
   text += f"""
[CHAPTER]
TIMEBASE=1/1000
START={start}
END={end}
title={title}
"""


with open("FFMETADATAFILE", "a") as myfile:
    myfile.write(text)

Thanks for any help provided.

Find elsewhere
๐ŸŒ
Devrevive
devrevive.com โ€บ convert โ€บ python-to-bash
Python to Bash Converter | DevRevive
Convert Python code to Bash instantly with AI-powered DevRevive converter. Perfect for developers and teams.
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ python-script-converter
python-script-converter ยท PyPI
This is a tiny tool used to convert a python script to a executable file(only for Mac and Linux).
      ยป pip install python-script-converter
    
Published ย  Jun 04, 2020
Version ย  1.2
๐ŸŒ
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.
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.

๐ŸŒ
IEEE Xplore
ieeexplore.ieee.org โ€บ document โ€บ 7081866
Bash2py: A bash to Python translator | IEEE Conference Publication | IEEE Xplore
Shell scripting is the primary way for programmers to interact at a high level with operating systems. For decades bash shell scripts have thus been used to accomplish various tasks. But Bash has a counter-intuitive syntax that is not well understood by modern programmers and is no longer ...
๐ŸŒ
AlgoDaily
algodaily.com โ€บ convert โ€บ bash โ€บ python
AlgoDaily - Daily coding interview questions. Full programming interview prep course and software career coaching.
Programming interview prep bootcamp with coding challenges and practice. Daily coding interview questions. Software interview prep made easy.
๐ŸŒ
Sisense Community
community.sisense.com โ€บ sisense community โ€บ deploy & connect analytics
Converting a working Python script into Bash to upload as Pre/Post Build Script | Sisense Community
I have a customized automation ... in Python using the Pysense library. We were planning to use this to upload as a Pre/Post build script on the elasticube end over the admin page to automate the script execution with the cube build. But according to the documentations, it says that it only allows a bash script. I do not have knowledge/ skill on bash scripts. Is there any easy way for me to convert this working ...
๐ŸŒ
bootvar
bootvar.com โ€บ how-to-convert-shell-script-to-python
How I converted my bash scripts into Python? - bootvar
October 20, 2022 - Python and Shell scripts are similar in nature as both are interpreted i.e. executed statement by statement. First of all you need to figure out what all things are used in existing shell script and figure out if any existing library is there for the same: ... Below are some useful libraries for above functionalities and in general for converting bash to Python.