VSCode中字典字符串命令行参数被sys.argv拆分多段的原因排查
Let's break down why this is happening and how to fix it:
The Root Cause
When you run your script directly in the terminal with:
some_script.py --arg1="{'a':'1','b':'2'}"
the shell interprets the outer quotes as a signal to treat the entire --arg1="{'a':'1','b':'2'}" as a single argument.
But in your VSCode launch.json config, you added extra quotes and escaping:
"args": ["--arg1=\"{'a':'1','b':'2'}\""]
The VSCode Python debugger doesn't use a shell to parse these arguments by default—each element in the args array is meant to be a direct, standalone argument for your script. By wrapping the argument in extra quotes, you're confusing the argument parser: it tries to interpret the inner quotes and commas as separators, splitting your single argument into two separate --arg1 entries.
The Fix
You don't need to add extra quotes or escape quotes in the args array. Just pass the argument as a single, unquoted string (or properly escaped for JSON if using double quotes):
Option 1: Use single quotes for the dictionary (no escaping needed in JSON)
"args": ["--arg1={'a':'1','b':'2'}"]
Option 2: Use double quotes for the dictionary (escape them for JSON compliance)
"args": ["--arg1={\"a\":\"1\",\"b\":\"2\"}"]
Either way, when you run import sys; print(sys.argv) in your script, you'll get the expected output:
['<cwd>/some_script.py', "--arg1={'a':'1','b':'2'}"]
Bonus Tip
If you ever need to pass arguments with spaces or special characters, just include them as a single element in the args array—VSCode handles the "wrapping" for you without needing explicit quotes.
内容的提问来源于stack exchange,提问作者Dan Erez

