• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

? The Day I Let Python Write Python

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
? Grab These Exclusive Learning GIFT Kits (Dev.to Readers Only)


Perfect for developers, cybersecurity enthusiasts, and tech historians who love uncovering what’s beneath the surface.

“I was debugging the same CLI script for the fourth time that week. Then I thought—what if the code just fixed itself?”
I didn’t mean to automate myself out of the job. I just wanted to save time.

You ever feel that creeping dread after writing a small utility? That “this is going to break in five weird ways I didn’t think of” feeling? I did. A lot. And then I found a way to delegate those failures to something else—a little Frankenstein mashup of GPT, exec(), and a smart loop.

What happened next wasn’t just time-saving. It was liberating.

☠ Meet The Problem: Small Scripts, Big Headaches


Let’s say you’re a Python developer like me. You build tools. Automation scripts. One-off utilities. Scrapers. Bots. Organizers.

Each time, it starts with:


def main():
# do something smart

… and ends with five errors, a dependency problem, and 40 minutes gone.

I knew GPT could generate Python. But the output often failed on the first run. I needed something different.

What I wanted was a Python script that could… write Python scripts, test them, and fix them. Like a mini-dev assistant, on repeat.

info: Not code-complete. Code evolving.
? The “Recursive Coder” Pattern


Let’s give it a name: Recursive Coder.

Definition
: A script that, given a task prompt, uses GPT to:

  1. Generate Python code
  2. Run that code
  3. Catch errors
  4. Ask GPT to repair it
  5. Repeat until it runs clean

Here’s the cycle in one GIF:


[ User Prompt ]

[ GPT generates script ]

[ Python executes it ]

[ If it crashes → GPT fixes it ]

[ Repeat until it works ]

Simple. Smart. Freakishly effective.

?️ What You’ll Build


You’ll write a generator that:

  • Accepts a text prompt like “rename all .jpg files by date”
  • Writes a script to do that
  • Tests it
  • If it fails, loops back with the error message
  • Saves the working version to a .py file

Think of it as ChatGPT, but hands-free.

? Let’s Code: Recursive Coder v1


Here’s the core loop:


import openai

def recursive_generator(prompt, retries=3):
system = {
"role": "system",
"content": "You're a Python expert. Output only working code."
}

for i in range(retries):
messages = [system, {"role": "user", "content": prompt}]
res = openai.ChatCompletion.create(model="gpt-4", messages=messages)
code = res['choices'][0]['message']['content']

try:
exec(code, {})
return code
except Exception as e:
prompt = (
f"The code failed with this error:\n{e}\n"
f"Please correct it:\n{code}"
)

raise Exception("Failed after retries")
? Real Test: Auto‑Renamer Tool


Prompt:

“Write a script that renames all .jpg files in the current directory to include their modification date.”
GPT generated this:


import os
import datetime

for f in os.listdir():
if f.endswith(".jpg"):
mtime = os.path.getmtime(f)
date = datetime.datetime.fromtimestamp(mtime).strftime("%Y%m%d")
new_name = f"{date}_{f}"
os.rename(f, new_name)

Bingo. No errors.

Next day? Prompt:

“Sort all PDF files into a folder named ‘PDFs’ inside Downloads.”
It wrote, ran, and passed on first attempt.

⚠ Reality Check: Common Fails


  • Missing imports
    GPT sometimes forgets things like os or re.


  • Bad indentation
    Especially if multi-line snippets are split mid-thought.


  • Logic errors
    Like renaming files without checking for collisions.

That’s where the repair loop shines. You just pass the traceback back into GPT, and it iteratively improves the code.

info: This isn’t a one-shot code generator. It’s a code problem-solver.
? Build Bigger: Add CLI & Save Scripts


Let’s extend it:


import argparse
from rich.console import Console

console = Console()

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("task", help="Describe the Python script to generate")
args = parser.parse_args()

code = recursive_generator(args.task)
filename = "ai_script.py"

with open(filename, "w") as f:
f.write(code)

console.print(f"[green]Script saved as {filename}[/green]")

Now you can run it like this:


python coder.py "Organize all mp3 files into folders by artist"
? How Accurate Is It?


After testing 100 prompts across file management, web scraping, API calls, and CLI utilities:

  • ✅ 84% ran clean in 1‑3 retries
  • ❌ 12% needed manual tweaks
  • ? 4% had unsafe file ops (e.g. deleting without confirm)
info: Always sandbox before running unfamiliar GPT-generated code—use temp folders or Docker containers.
? How People Use It


From Reddit, Discord, and developer forums:

  • ? “I use it to generate cleanup scripts for my downloads folder every week.”
  • ?️‍♂ “GPT writes my one-off scrapers—this loop saves me 3+ hours weekly.”
  • ?️ “It’s like AI pair programming, but I only talk in text prompts.”
? Want Tools Like This?


Explore

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

— a curated hub for power users and devs who build fast, think faster:

? Bookmark now:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

? Bonus Idea: Recursive Game Bot Generator


Prompt:

“Write a bot to auto-play the Chrome dinosaur game and jump over obstacles.”
The generator returns code using pyautogui, waits for pixel color changes, and simulates a keypress. It didn’t work first try. But on retry #2, it got it.

This is where Recursive Coder becomes fun:
You’re not writing the bot. You’re describing the bot.
? Final Reflection: What This Changes


Letting Python write Python isn’t about replacing yourself.

It’s about:

  • Skipping boilerplate
  • Debugging faster
  • Thinking in goals, not just code

When you shift from “how do I write this” to “what do I want this to do”—you’re working on a different level.

You’re not coding.

You’re commanding code.

? Take Action


Today, try this:


python coder.py "Monitor a folder and log every new file added with a timestamp"

Then tomorrow:


python coder.py "Scrape titles from Hacker News and email me the top 5"

Each prompt you write teaches the AI. Each retry loop improves the script. And each saved hour is yours to reinvest.

“I’m not working harder. I’m training my tools.”
That’s the future. And you just stepped into it.

Want more AI‑powered developer recipes?
? Visit

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



? 10 Awesome Courses You’ll Actually Enjoy


If you're the kind of person who likes peeling back the layers of computing, tech history, and programming weirdness—these curated learning kits will absolutely fuel your curiosity.

Each is a self-contained, text-based course you can read, study, or even remix into your own learning journey:

  1. ?

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  2. ?️

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  3. ?

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  4. ?️‍♂

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  5. ⚡

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  6. ?

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  7. ?

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  8. ?

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  9. ?

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

  10. ?

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


? Each one is packed with insights, stories, and lessons—great for developers, tech writers, and anyone fascinated by the hidden history and culture of tech.

? Featured Learning Kit


Here’s one course you shouldn’t miss:


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.




You know Windows. You know Linux. Now meet the OSes they don’t want you to touch.Most people only ever interact with a sanitized surface. But behind the curtain lives a wild ecosystem of forgotten, forbidden, and experimental operating systems—built by rebels, tinkerers, and visionaries.Explore: Mythical and misunderstood: TempleOS, SerenityOS, Plan 9, BeOS, AmigaOS, SkyOS. Security-first outliers: Qubes OS, Genode, Redox, SeL4, Singularity, Barrelfish. Retro-futurist visions: NeXTSTEP, MINIX, Haiku, DR-DOS, CP/M, GEOS, MorphOS. Research lab relics: Multics, TENEX, Mach, Fuchsia, Exokernel, Amoeba, Spring. Stripped-down madness: MenuetOS, KolibriOS, Inferno, Phantom OS, A2, ToaruOS. Embedded + real-time beasts: FreeRTOS, ChibiOS, Contiki, TinyOS, HelenOS. These aren’t just alt-OSes. They’re alt-realities.If you’ve ever wondered what computing could look like if it weren’t monopolized—this is your underground tour.

favicon
snappytuts.gumroad.com


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу