Running Claude Code in Batches for Automated Workflows

Learn how to run Claude Code in batches using Python. Automate long-running AI coding tasks with process control, timeouts, and graceful termination.

I had 262 items to process. Claude Code’s context window gets foggy after handling about 25 items. So I needed to run it in batches, automatically resuming where it left off.

The solution? A Python script that launches Claude Code, waits for it to work, then gracefully shuts it down and starts fresh.

The Batch Runner

# run_claude_in_batches.py
import subprocess
import time
import signal

def one_go():
    PROMPT = "resume with a batch size of 5"
    WAIT_MINUTES = 5

    complete_command = """claude --permission-mode bypassPermissions 'resume with a batch size of 5'"""
    print(f"Command: {complete_command}")

    process = subprocess.Popen(complete_command, shell=True, cwd=".", text=True)
    print(f"Claude Code started (PID={process.pid})")

    print(f"Waiting {WAIT_MINUTES} minutes...")
    time.sleep(WAIT_MINUTES * 60)

    print("Sending SIGINT...")
    process.send_signal(signal.SIGINT)

    try:
        process.wait(timeout=5)
    except subprocess.TimeoutExpired:
        print("Force terminating Claude Code...")
        process.kill()

if __name__ == "__main__":
    count = int(262/25)
    for i in range(count):
        print(f"Run {i+1}/{count}")
        one_go()
    print("Done.")

How It Works

  1. Launch Claude Code with bypassPermissions mode so it can run unattended
  2. Let it work for a fixed time window (5 minutes in this case)
  3. Send SIGINT to gracefully shut down, allowing Claude to save state
  4. Force kill if it doesn’t respond within 5 seconds
  5. Loop until all batches are processed

The key insight: Claude Code can resume work when you tell it to. The “resume with a batch size of 5” prompt leverages this. You need to have your task structured so Claude knows what “resume” means - typically by having it track progress in a file or database.

When This Pattern Fits

This works well when:

  • You have many similar items to process
  • Each item is independent
  • Claude can track its own progress
  • You’re running overnight or unattended

It’s probably overkill for:

  • Interactive development sessions
  • Tasks requiring human judgment at each step
  • One-off operations

The batch size and wait time are tunable. Start with shorter waits and adjust based on how much work Claude typically completes per cycle.

About the Author

Ashish Anand

Ashish Anand

Founder & Lead Developer

Full-stack developer with 10+ years experience in Python, JavaScript, and DevOps. Creator of DevGuide.dev. Previously worked at Microsoft. Specializes in developer tools and automation.