Shell Script: Execute a python program from within a shell script Shell Script: Execute a python program from within a shell script python python

Shell Script: Execute a python program from within a shell script


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/shpython 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.pyCreate a file called job.sh that contains

#!/bin/bashpython 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


Imho, writing

python /path/to/script.py

Is quite wrong, especially in these days. Which python? python2.6? 2.7? 3.0? 3.1? Most of times you need to specify the python version in shebang tag of python file. I encourage to use

#!/usr/bin/env python2 #or python2.6 or python3 or even python3.1
for compatibility.

In such case, is much better to have the script executable and invoke it directly:

#!/bin/bash/path/to/script.py

This way the version of python you need is only written in one file. Most of system these days are having python2 and python3 in the meantime, and it happens that the symlink python points to python3, while most people expect it pointing to python2.