Search code examples
pythonshebang

Should I put the shebang line in every python file?


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?


Solution

  • 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.