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
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
Method 1 - Create a shell script:
Suppose you have a python file hello.py
Create a file called job.sh that contains
#!/bin/bash
python hello.py
mark it executable using
$ chmod +x job.sh
then run it
$ ./job.sh
Method 2 (BETTER) - Make the python itself run from shell:
Modify your script hello.py and add this as the first line
#!/usr/bin/env python
mark it executable using
$ chmod +x hello.py
then run it
$ ./hello.py
How can I call a shell script from Python code? - Stack Overflow
Run Python Code in a Shell Script
How to include python script inside a bash script - Unix & Linux Stack Exchange
From Bash to Python
Can I execute shell commands directly from Python scripts?
How does Python compare to traditional shell scripting languages like Bash?
How can I optimize Python shell scripts for performance?
Videos
The subprocess module will help you out.
Blatantly trivial example:
>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0
Where test.sh is a simple shell script and 0 is its return value for this run.
There are some ways using os.popen() (deprecated) or the whole subprocess module, but this approach
import os
os.system(command)
is one of the easiest.
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!
Just pass a HereDoc to python -.
From python help python -h:
- : program read from stdin
#!/bin/bash
MYSTRING="Do something in bash"
echo $MYSTRING
python - << EOF
myPyString = "Do something on python"
print myPyString
EOF
echo "Back to bash"
You can use heredoc if you want to keep the source of both bash and python scripts together. For example, say the following are the contents of a file called pyinbash.sh:
#!/bin/bash
echo "Executing a bash statement"
export bashvar=100
cat << EOF > pyscript.py
#!/usr/bin/python
import subprocess
print 'Hello python'
subprocess.call(["echo","$bashvar"])
EOF
chmod 755 pyscript.py
./pyscript.py
Now running pyinbash.sh will yield:
$ chmod 755 pyinbash.sh
$ ./pyinbash.sh
Executing a bash statement
Hello python
100
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.
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
echowithprint. - Replace your loop with
for r in range(runs):. - Get the
datewith the datetime module. - Replace write to file with the file objects module.
- Replace the call to
db2with the subprocess module. - You'll need to
import reads.pyto 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.