
Every Python Script I Write Starts With These 15 Lines
After writing Python professionally for 6 years, I've settled on a boilerplate that saves me from the same 5 bugs every time. Here are the 15 lines I paste at the top of every new script: #!/usr/bin/env python3 """ [Description of what this script does]. """ import argparse import json import logging import sys from pathlib import Path logging . basicConfig ( level = logging . INFO , format = " %(asctime)s %(levelname)s %(message)s " , datefmt = " %H:%M:%S " , ) log = logging . getLogger ( __name__ ) Let me explain why each line matters. Line 1: The Shebang #!/usr/bin/env python3 Without this, ./script.py fails on Linux/Mac. With it, the system finds Python automatically. env python3 is more portable than /usr/bin/python3 because Python might be installed anywhere. Lines 4-7: The Right Imports import argparse import json import logging import sys from pathlib import Path argparse — Every script eventually needs command-line arguments. Adding it later means refactoring sys.argv hacks. S
Continue reading on Dev.to Python
Opens in a new tab




