Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I put the shebang line in every python file?

Tags:

python

shebang

I am working on a medium sized python (2.7) project with multiple files I import. I have one main python file which starts the program. Other files contain class definitions, functions, etc.

I was wondering if I should put the shebang line in every python file or only the one I run in order to start my program?

like image 221
ap0 Avatar asked Oct 30 '14 10:10

ap0


2 Answers

Only files which you will execute by invoking them directly require the shebang. Small hint: if a file contains

if __name__ == "__main__":
    main()

it is better (to stick with the Least Astonishment principle) to start it with a shebang. Make sure to have that shebang robust; rather have

#!/usr/bin/env python

than

#!/usr/bin/python

Many module files contain a main method used to start tests, so many module files start with a shebang.

like image 106
damienfrancois Avatar answered Sep 29 '22 14:09

damienfrancois


It depends. The short answer is that you only need the #! line if the file is to be executed as a main program. You might take that as meaning only one file needs it. But....

It is a common pattern to write modules for use as both a component and a main program. This (at the very least) can aid testing. The module can be tested on its own without the rest of the program. The trick is to put this at the end of the program:

if __name__ == '__main__':
    # Run some tests, or other stuff here

That way, it can exist as a main program. It is very common to have a function called main and call it from the if statement, but that is not mandatory.

like image 43
cdarke Avatar answered Sep 29 '22 13:09

cdarke