Introduction
I wanted to automate GitHub Copilot CLI calls from Python using subprocess, but it kept failing unexpectedly.
After some investigation, I found that this isn’t a Copilot CLI-specific issue—it’s a common pitfall when automating CLI tools on Windows + PowerShell. Here’s what I learned.
Table of Contents
What Happened
When trying to call Copilot CLI with subprocess.run(), I encountered several issues:
- Quoting/escaping breaks (especially with
", newlines, or special characters in prompts) - Command becomes too long (long prompts or paths can trigger
WinError 206) - CLI hangs waiting for interactive input
Important: You Need --add-dir for File Editing
If you want Copilot to edit or output files, you must explicitly specify the target directories. Otherwise, Copilot won’t have access to read or write files, and the operation will fail.
--add-dir "<prompt_dir>"
--add-dir "<out_dir>"Solution 1: Call via PowerShell
Wrapping the command with PowerShell’s -Command tends to work better. This approach worked for me.
cmd_str = f'powershell.exe -Command "copilot -p \\\"{escaped_prompt}\\\" --model {model} --allow-all-tools --add-dir \\\"{prompt_dir}\\\" --add-dir \\\"{out_dir}\\\""'Solution 2 (Recommended): Pass Prompt as Arguments
To avoid quoting issues with long commands, pass the prompt via PowerShell’s param mechanism instead of embedding it directly in -Command.
import subprocess
ps = r'param($p,$m,$pd,$od) copilot -p $p --model $m --allow-all-tools --add-dir $pd --add-dir $od'
subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", ps,
"--", prompt, model, prompt_dir, out_dir],
text=True,
capture_output=True,
)Summary
- If your prompt contains
"or newlines, avoid string embedding (use the param approach) - For file editing/output, always include
--add-dir - Add
-NoProfile/-NonInteractivefor stable execution

