“Boilerplate” code in Python?

后端 未结 6 863
终归单人心
终归单人心 2021-02-01 03:07

Google has a Python tutorial, and they describe boilerplate code as \"unfortunate\" and provide this example:

#!/usr/bin/python

# import modules used here -- sy         


        
6条回答
  •  忘了有多久
    2021-02-01 03:12

    You don't need to add a if __name__ == '__main__' for one off scripts that aren't intended to be a part of a larger project. See here for a great explanation. You only need it if you want to run the file by itself AND include it as a module along with other python files.

    If you just want to run one file, you can have zero boilerplate:

    print 1
    

    and run it with $ python your_file.py

    Adding the shebang line #!/usr/bin/python and running chmod +x print_one.py gets you the ability to run with

    ./print_one.py

    Finally, # coding: utf-8 allows you to add unicode to your file if you want to put ❤'s all over the place.

提交回复
热议问题