pythonpowershellargparse

Python argparse not working corrrectly with path in Windows


The argparse library in python doesn't work for any path containing a space and \ (backslash) at the end. The parser will parse the backslash at the end of path to be " (double quotation).

The code below is a sample that has same problem:

import argparse


if __name__=="__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-w', '--weight', type=str)

    args = parser.parse_args()

    print(args.weight_path)

For example in PowerShell:

PS > python sample.py -w ".\test test\"
.\test test"

It does work for any path which doesn't contain a space:

PS > python sample.py -w ".\testtest\"
.\test test\
PS > python sample.py -w "testtest\"
test test\
PS > python sample.py -w "testtest"
test test

Is there any issues with using argparse with PowerShell?

I don't even know how to search for a solution to this problem...


Solution

  • You're seeing what is a bug in Windows PowerShell, which has since been corrected in PowerShell (Core) 7+:

    The workaround for Windows PowerShell is to manually double the \ char. before the closing ":

    # Windows PowerShell only: double the \ before the closing "
    python sample.py -w ".\test test\\"
    

    As an aside:


    [1] Note that an argument without spaces, e.g. .\test_test\, would not cause the problem, because PowerShell - when it builds the true process command line behind the scenes - does not enclose such arguments in "..." (does not double-quote them).