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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With