I have a Python script and I was wondering how I can make it executable; in other words how can I run it by using a shell like bash.
I know the first thing is to stick on the first line #! /usr/bin/env python
but then do I need for example the functions to be in a specific order (i.e., the main one at the top or the bottom). What's more do I need to keep the extension .py for my python file (can I just call the function Dosomething
?).
To be short, could you provide a simple guide, the important points someone has to take into account to make a Python file executable?
This is how I make an executable script. It doesn't take
eggs
or anything like that into account. It's just a simple script that I want to be able to execute. I'm assuming you are using linux.Now, if you're permissions are set correctly, you can execute this script.
One thing to realize is as your script is processed each line is executed in the interpreter. This is true, regardless of how the processor "gets it". That is importing a script as a module and executing it as a script essentially both work the same, in that they both execute each line of the module.
Once you realize your script is simply executing as it runs, you realize that the order of functions don't matter. A function declaration is a function declaration. It's when you call the function that matters.
So, in general, the layout of your script looks like this
You create the functions you want to use first, then you use them. Hope it helps.
#!/usr/bin/python
in the first linemyPythonScript
(No, you do not need to keep .py extension)chmod +x myPythonScript
./myPythonScript
Example: myPythonScript
Your code should follow the template
If you want to be able to run it without having to use
python fileName.py
but rather just./fileName.py
then you will want to make the first line of your fileAnd make the file executable by the user at least
If you do not add a .py extension to your file then it will still be runnable from the command line ... but not importable by other modules.
The only thing (like you said it) is to include:
on the first line. And is not even mandatory, but recommended. After that, you can just call it writing:
in a terminal or in a bash file.
You need to add sha bang as you described, e.g.
or
as the first line in your file and you need to make it executable by running
You do not need to do anything else, in particular file name may be anything including
Dosomething
. YourPATH
probably doesn't include the directory where the file resides, so you should run it like this (assuming your current working directory is where the file is):You'll also have to give it execution rights: