๐ŸŒ
Moran Nachum
morannachum.wordpress.com โ€บ 2020 โ€บ 03 โ€บ 22 โ€บ how-to-convert-a-python-script-to-a-shell-script
How to Convert a Python Script to a Shell Script | Moran Nachum
March 23, 2020 - But, just to be safe that the Shell script will continue to work even if I moved it outside of its original directory, I formatted it as follows: #!/bin/sh cd "$(dirname "$0")"; CWD="$(pwd)" echo $CWD /Users/mnachum/Desktop/how\ to\ troubleshoot\ crontab/hello/bin/python /Users/mnachum/Desktop/how\ to\ troubleshoot\ crontab/hello_world.py
Discussions

Converting a bash script to python (small script) - Stack Overflow
Sorry, why is cygwin bash a problem? ... bash shell, you will just need to know the cygwin path, even then i know cygwin can do some windows to cygwin path conversion. For example you could call /cygdrive/c/programfiles/db2 , assuming of course that you have a non-cygwin db2 implementation that you want to use. Additionally , you can even call the windows python interpreter to run your script instead of ... 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
How to convert this Python code into a shell script? - Stack Overflow
Each time I want to download 7 files for seven sequential days, so I need to use a logic like above to download files. How to covert this python code above into a shell script? More on stackoverflow.com
๐ŸŒ stackoverflow.com
September 2, 2022
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.

๐ŸŒ
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
๐ŸŒ
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.
๐ŸŒ
Better Programming
betterprogramming.pub โ€บ build-your-python-script-into-a-command-line-tool-f0817e7cebda
Converting Python Script Into a Command-line Tool | by Liu Zheng | Better Programming
June 15, 2022 - Converting Python Script Into a Command-line Tool Wrap your Python script into an installable command-line tool using pip Python is a handy language for writing scripts and building tools. Most โ€ฆ
Find elsewhere
๐ŸŒ
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.

๐ŸŒ
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%
๐ŸŒ
Blogger
hadoopquiz.blogspot.com โ€บ home โ€บ python queries
How to Convert Python script to shell script online
July 10, 2023 - Then it collects copies of all those files โ€“ including the active Python interpreter! โ€“ and puts them with your script in a single folder, or optionally in a single executable file. For the great majority of programs, this can be done with one short command, ... Respect Others Opinion. Commenting Link Is Strictly Forbidden. Comments According To The Posts Always Gets Priority.
๐ŸŒ
GitHub
github.com โ€บ yunabe โ€บ pysh
GitHub - yunabe/pysh: Write shell scripts in Python
In pysh, lines that starts with > are executed as shell command. Other lines are evaluated as normal Python script. for i in xrange(100): index = "d" % i > mv from$index.txt to$index.txt
Starred by 47 users
Forked by 6 users
Languages ย  Python 100.0% | Python 100.0%
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 73578165 โ€บ how-to-convert-this-python-code-into-a-shell-script
How to convert this Python code into a shell script? - Stack Overflow
September 2, 2022 - import datetime def get_a_week(start) date = datetime.datetime(start) dates = [] for i in range(7): date += datetime.timedelta(days=1) print(date) dates.app...
๐ŸŒ
grep Flags
zwischenzugs.com โ€บ 2016 โ€บ 08 โ€บ 29 โ€บ bash-to-python-converter
Bash to Python Converter โ€“ zwischenzugs.com
August 29, 2016 - Iโ€™d recommend mounting the directory of an existing shell script into the container when calling docker run: docker run -v /abs/path/to/file/dir:/somemountedfolder -ti imiell/bash2py Log in to Reply
๐ŸŒ
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
The great coreutils like grep, ... designed to go over text files line by line and do... something with the content of that line. Any shell scripter knows that these "files" aren't always really files. Often as not, it's really dealing with the output of another process and not a file at all. Whatever the source, the organizing principle is streams of text divided by newline characters. In Python, this is what ...
Starred by 1.1K users
Forked by 112 users
๐ŸŒ
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 script for row level security written in Python using the Pysense library. We were planning to use this to upload as a...
๐ŸŒ
myByways
mybyways.com โ€บ blog โ€บ migrating-from-bash-shell-scripts-to-python
Migrating from bash shell scripts to Python | myByways
March 11, 2021 - Python has many string functions which are a lot more usable e.g. find(), index(), join(), replace(), split(), strip(), etc. a="this is a long string" echo ${#a} # 21 echo ${a:8} # "a long string" echo ${a:8:4} # "a lo" echo ${a::4} # "this" echo ${a: -6} # "string" a="this is a long string" print(len(a)) print(a[8:]) print(a[8:12]) print(a[:4]) print(a[-6:]) Check for redirection using -t e.g. ./script.sh &gt; x.txt or ./script.sh | cat.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-run-bash-script-in-python
How to run bash script in Python? - GeeksforGeeks
September 13, 2022 - We can also execute an existing a bash script using Python subprocess module. ... import subprocess # If your shell script has shebang, # you can omit shell=True argument.