4

I have a python program in that I wrote some python code (disk.py). I executed this program using the command python disk.py in a terminal, it worked.

Now I want to execute it using a shell script.

  • 1
    You mean executing like ./disk.py (wild guess)? If so, you just need to add a suitable hash-bang, i.e. #!/usr/bin/python. If you mean some else, you need to clarify what you are talking about. – Faheem Mitha Mar 1 '14 at 9:06
  • First, rewrite the program logic in Shell script. Or I'm confused! – SparKot Mar 1 '14 at 9:22
11

To be able to execute as ./disk.py you need two things:

  1. Change the first line to this: #!/usr/bin/env python
  2. Make the script executable: chmod +x disk.py
  • why we need to write like this #/usr/bin/env python. what's purpose for env python – Beginner Mar 1 '14 at 9:43
  • @rajcoumar it's more portable this way. In some systems python might be in /usr/bin/python, in others it might be /opt/bin/python. With #!/usr/bin/env python it should work in all systems where python is correctly installed, regardless of its exact location. – janos Mar 1 '14 at 10:18
  • 1
    Isn't it python script rather than shell script ? – SHW Mar 18 '14 at 8:34
16

Shell script should be like:

#!/bin/sh
python disk.py
  • 1
    This answer actually addresses the Original Question better, because the latter clearly says "execute python program in a shell script" – DarkCygnus Jun 8 '17 at 23:41
1

As @SHW mentioned, the question actually asks about executing a python program in a shell script (not running the python script directly with ./disk.py)

So, expanding on @SHW answer, your shell script should be like:

#!/bin/bash
/usr/bin/python /absolute/path/to/your/disk.py

Notice the /usr/bin/python instead of just python; using absolute paths helps the script to know exactly what python to use (to find the absolute path to your installed python use which python).

Same story when using absolute paths with your python script instead of just disk.py. In my case, I was trying to run a Django app from my bash script, so I had to add the absolute path of my manage.py for it to run correctly.

Also, regarding the header of your bash script, there are several alternatives to #!/bin/bash. Please, take a look at this question to know more about it.

Cheers.

  • 1
    +1 for answering the actual question. ALSO thanks for including the python path. That solved the problem I was having! – Jim Aug 11 '17 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.