ChatGPT Python Script Builder Prompt
Build complete production-ready Python scripts for automation, data processing, and utility tasks with full error handling and documentation.
Category
💻 Coding
Difficulty
Intermediate
Models
3
Last Updated
2026-06-29
Works with
📄 Example output
⚠️ Common Mistakes
❓ FAQ
⚙️ Fill in your variables
📋 Prompt
You are a senior Python developer who writes clean production-ready scripts.
Task: [describe exactly what the script should do]
Inputs: [what data or files it receives]
Outputs: [what it should produce]
Python version: [3.9/3.10/3.11/3.12]
Dependencies: [only stdlib / specific packages / anything]
Error handling: [basic / robust — handle all edge cases]
Task:
1. COMPLETE SCRIPT: Working code with all imports, type hints throughout, docstrings on all functions, constants at top, main guard
2. ERROR HANDLING: Specific exceptions caught, meaningful messages, graceful degradation
3. USAGE EXAMPLES: How to run from command line
4. DEPENDENCIES: pip install command if needed
5. EDGE CASES: What the script handles and what it does not
6. TESTS: 3-5 test cases as assertions or pytest
Task: [describe exactly what the script should do]
Inputs: [what data or files it receives]
Outputs: [what it should produce]
Python version: [3.9/3.10/3.11/3.12]
Dependencies: [only stdlib / specific packages / anything]
Error handling: [basic / robust — handle all edge cases]
Task:
1. COMPLETE SCRIPT: Working code with all imports, type hints throughout, docstrings on all functions, constants at top, main guard
2. ERROR HANDLING: Specific exceptions caught, meaningful messages, graceful degradation
3. USAGE EXAMPLES: How to run from command line
4. DEPENDENCIES: pip install command if needed
5. EDGE CASES: What the script handles and what it does not
6. TESTS: 3-5 test cases as assertions or pytest
```python
#!/usr/bin/env python3
from pathlib import Path
from typing import NamedTuple
import csv, time
import requests
from requests.exceptions import Timeout, ConnectionError, RequestException
TIMEOUT_SECONDS: int = 10
USER_AGENT: str = 'URLChecker/1.0'
class URLResult(NamedTuple):
url: str
status_code: int | None
response_time_ms: int | None
status: str
error: str
def check_url(url: str) -> URLResult:
if not url.startswith(('http://', 'https://')):
return URLResult(url, None, None, 'error', 'Invalid URL: missing scheme')
try:
start = time.monotonic()
r = requests.get(url, timeout=TIMEOUT_SECONDS, headers={'User-Agent': USER_AGENT})
ms = int((time.monotonic() - start) * 1000)
return URLResult(url, r.status_code, ms, 'working' if r.status_code == 200 else 'broken', '')
except Timeout:
return URLResult(url, None, None, 'error', f'Timeout after {TIMEOUT_SECONDS}s')
except ConnectionError as e:
return URLResult(url, None, None, 'error', f'Connection failed: {e}')
except RequestException as e:
return URLResult(url, None, None, 'error', str(e))
def read_urls(path: Path) -> list[str]:
with open(path, newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
if 'url' not in (reader.fieldnames or []):
raise ValueError("CSV must have a 'url' column")
return [row['url'].strip() for row in reader if row['url'].strip()]
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print('Usage: python url_checker.py input.csv output.csv'); sys.exit(1)
results = [check_url(u) for u in read_urls(Path(sys.argv[1]))]
with open(sys.argv[2], 'w', newline='', encoding='utf-8') as f:
w = csv.writer(f)
w.writerow(['url','status_code','response_time_ms','status','error'])
for r in results: w.writerow([r.url, r.status_code, r.response_time_ms, r.status, r.error])
print(f'Done: {sum(1 for r in results if r.status=="working")}/{len(results)} working.')
```
USAGE: pip install requests then python url_checker.py urls.csv report.csv
#!/usr/bin/env python3
from pathlib import Path
from typing import NamedTuple
import csv, time
import requests
from requests.exceptions import Timeout, ConnectionError, RequestException
TIMEOUT_SECONDS: int = 10
USER_AGENT: str = 'URLChecker/1.0'
class URLResult(NamedTuple):
url: str
status_code: int | None
response_time_ms: int | None
status: str
error: str
def check_url(url: str) -> URLResult:
if not url.startswith(('http://', 'https://')):
return URLResult(url, None, None, 'error', 'Invalid URL: missing scheme')
try:
start = time.monotonic()
r = requests.get(url, timeout=TIMEOUT_SECONDS, headers={'User-Agent': USER_AGENT})
ms = int((time.monotonic() - start) * 1000)
return URLResult(url, r.status_code, ms, 'working' if r.status_code == 200 else 'broken', '')
except Timeout:
return URLResult(url, None, None, 'error', f'Timeout after {TIMEOUT_SECONDS}s')
except ConnectionError as e:
return URLResult(url, None, None, 'error', f'Connection failed: {e}')
except RequestException as e:
return URLResult(url, None, None, 'error', str(e))
def read_urls(path: Path) -> list[str]:
with open(path, newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
if 'url' not in (reader.fieldnames or []):
raise ValueError("CSV must have a 'url' column")
return [row['url'].strip() for row in reader if row['url'].strip()]
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print('Usage: python url_checker.py input.csv output.csv'); sys.exit(1)
results = [check_url(u) for u in read_urls(Path(sys.argv[1]))]
with open(sys.argv[2], 'w', newline='', encoding='utf-8') as f:
w = csv.writer(f)
w.writerow(['url','status_code','response_time_ms','status','error'])
for r in results: w.writerow([r.url, r.status_code, r.response_time_ms, r.status, r.error])
print(f'Done: {sum(1 for r in results if r.status=="working")}/{len(results)} working.')
```
USAGE: pip install requests then python url_checker.py urls.csv report.csv
🏆
💡 Pro Tips
Best model for this prompt
DeepSeek
DeepSeek V3 / R1
Type hints make scripts self-documenting and enable IDE support — always include them in production code
Constants at the top make configuration changes one-line edits
The main guard lets the script be imported as a module without running — always include it
Catch specific exceptions not bare Exception — gives far more useful error messages to the user
No error handling at all — network scripts always encounter failures; unhandled exceptions give cryptic messages
Hardcoded file paths and magic numbers — use constants and command-line arguments
No type hints — makes code harder to maintain and understand six months later
Missing encoding parameter in file opens — prevents surprises on non-ASCII content
- Should I use asyncio for URL checking?For 100+ URLs, asyncio with aiohttp gives massive performance gains. For smaller lists the synchronous approach is simpler. Use ThreadPoolExecutor as a middle ground without the async complexity.
- How to make the script faster?Use concurrent.futures.ThreadPoolExecutor for I/O-bound tasks. For 100 URLs, 10 parallel workers reduces total time from 100s to about 10s.
- Best model for Python scripts?DeepSeek V3 writes clean idiomatic Python with excellent error handling and modern conventions. Claude is also excellent and better at explaining implementation trade-offs.
- How to handle very large CSV files?Replace the list comprehension in read_urls with a generator and process in batches. Memory stays constant regardless of file size.