Last active
February 25, 2026 18:15
-
-
Save pavel-kirienko/a7068fedbfee41ffcaea9f8338136366 to your computer and use it in GitHub Desktop.
Ultimate disposable software generator: describe what needs to be done in command line arguments, get a script that does that and run it, dispose the script immediately
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # | |
| # A simple CLI utility that accepts natural-language description of what needs to be done and provides a Python | |
| # script doing just that, with an option to run it immediately. The tool requires no dependencies and runs anywhere. | |
| # | |
| # 1shot.py find the largest file in this directory excluding hidden directories | |
| # 1shot.py count lines of Python code excluding blanks and comments, show top 10 | |
| # | |
| # Quotes are not necessary, just write the prompt like you normally would. | |
| # | |
| # To install, simply save the script and make it executable. | |
| # | |
| # --------------------------------------------------------------------------------------------------------------------- | |
| # MIT License | |
| # Pavel Kirienko <pavel.kirienko@gmail.com> | |
| import os | |
| import re | |
| import sys | |
| import socket | |
| from pathlib import Path | |
| import urllib.request | |
| import json | |
| import subprocess | |
| import tempfile | |
| from datetime import datetime | |
| from importlib.metadata import distributions | |
| def is_sensitive_env_name(name: str) -> bool: | |
| sensitive = "KEY", "TOKEN", "SECRET", "PASSWORD", "PASSWD", "PASS", "AUTH", "COOKIE", "CREDENTIAL", "PRIVATE" | |
| upper = name.upper().replace("-", "_") | |
| tokens = [x for x in upper.split("_") if x] | |
| return any(marker in tokens for marker in sensitive) or any( | |
| marker in upper for marker in ("API_KEY", "ACCESS_KEY", "SECRET_KEY", "PRIVATE_KEY", "BEARER") | |
| ) | |
| def sanitize_environment(env): | |
| out = {} | |
| for key, value in sorted(env.items()): | |
| value = str(value) | |
| if is_sensitive_env_name(key): | |
| out[key] = "<REDACTED>" | |
| else: | |
| out[key] = value | |
| return out | |
| def build_system_prompt() -> str: | |
| env_vars = sanitize_environment(dict(os.environ)) | |
| env_vars_list = "\n".join(f"{k}={v}" for k, v in env_vars.items()) | |
| packages = sorted(f"{d.metadata['Name']}=={d.version}" for d in distributions() if "Name" in d.metadata) | |
| packages_list = "\n".join(packages) | |
| now = datetime.now().astimezone().strftime("%Y-%m-%dT%H:%M:%S%z (%a)") | |
| return f""" | |
| You are a computer use assistant. The user describes what needs to be done. | |
| You reply with a Python script that does what is needed, ready for execution as-is; | |
| respond ONLY with executable code and nothing else. | |
| Feel free to use `os.system(...)` or `subprocess.run(...)` if it's more convenient to invoke shell directly. | |
| The script may invoke AI APIs to accomplish the task if it is deemed complex enough to require reasoning. | |
| # Execution environment | |
| - Platform: {sys.platform} | |
| - Python version: {sys.version} | |
| - Hostname: {socket.gethostname()} | |
| - Current date and time: {now} | |
| ## Environment variables | |
| ``` | |
| {env_vars_list} | |
| ``` | |
| ## Installed Python packages | |
| ``` | |
| {packages_list} | |
| ``` | |
| """ | |
| def strip_markdown_fences(text: str) -> str: | |
| text = text.strip() | |
| if not text.startswith("```"): | |
| return text | |
| lines = text.splitlines() | |
| if not lines or not lines[0].startswith("```"): | |
| return text | |
| lines = lines[1:] | |
| for i, line in enumerate(lines): | |
| if line.strip().startswith("```"): | |
| lines = lines[:i] | |
| break | |
| return "\n".join(lines).strip() | |
| def generate(prompt: str) -> str: | |
| if openai_key := os.getenv("OPENAI_API_KEY", ""): | |
| data = { | |
| "model": "gpt-5.2", | |
| #"reasoning_effort": "minimal", | |
| "messages": [ | |
| {"role": "developer", "content": build_system_prompt()}, | |
| {"role": "user", "content": prompt}, | |
| ], | |
| } | |
| req = urllib.request.Request( | |
| "https://api.openai.com/v1/chat/completions", | |
| data=json.dumps(data).encode(), | |
| headers={"Content-Type": "application/json", "Authorization": f"Bearer {openai_key}"}, | |
| ) | |
| with urllib.request.urlopen(req) as r: | |
| data = json.loads(r.read()) | |
| return strip_markdown_fences(data["choices"][0]["message"]["content"]) | |
| elif anthropic_key := os.getenv("ANTHROPIC_API_KEY", ""): | |
| raise RuntimeError("Please add Anthropic support") | |
| else: | |
| raise RuntimeError("Inference API key missing") | |
| def main(): | |
| script = None | |
| if len(sys.argv) < 2: | |
| print("Describe what needs to be done.", file=sys.stderr) | |
| sys.exit(1) | |
| try: | |
| text = generate(" ".join(sys.argv[1:])) | |
| fd, path = tempfile.mkstemp(prefix="1shot_", suffix=".py", text=True) | |
| script = Path(path) | |
| with os.fdopen(fd, "w", encoding="utf-8") as f: | |
| f.write(text) | |
| bar = "━" * 80 | |
| print(bar, highlight_python(text), bar, file=sys.stderr, sep="\n") | |
| if input(f"Script temporarily stored into '{script}'. Run it now? [y/N] ").lower().strip() == "y": | |
| subprocess.run([sys.executable, str(script)]) | |
| except KeyboardInterrupt: | |
| pass | |
| except Exception as ex: | |
| print("Error:", ex, file=sys.stderr) | |
| sys.exit(1) | |
| def highlight_python(code: str) -> str: | |
| """ | |
| This is very simple and is known to miscolor certain edge cases, but it's good enough for this script. | |
| We can replace it with the built-in tokenizer module if we need strict conformance but it's probably too complex. | |
| """ | |
| RESET = "\033[0m" | |
| rules = [ | |
| (r'("""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\')', "\033[33m"), # triple-quoted strings | |
| (r'("(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\')', "\033[33m"), # strings | |
| (r"(#[^\n]*)", "\033[90m"), # comments | |
| (r"\b(def|class|return|if|elif|else|for|while|" | |
| r"try|except|finally|with|as|import|from|in|" | |
| r"not|and|or|is|None|True|False|raise|yield|" | |
| r"pass|break|continue|lambda|async|await)\b", "\033[94m"), # keywords | |
| (r"\b(\d+\.?\d*)\b", "\033[36m"), # numbers | |
| (r"^(\s*@[\w.]+)", "\033[35m"), # decorators | |
| ] | |
| for pattern, color in rules: | |
| code = re.sub(pattern, lambda m, c=color: c + m.group(0) + RESET, code) | |
| return code | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment