[New-bugs-announce] [issue39845] Argparse on Python 3.7.1 (Windows) appends double quotes to string if it ends with backward slash

Ion Cebotari report at bugs.python.org
Wed Mar 4 03:40:21 EST 2020


New submission from Ion Cebotari <anathemizatu at mail.ru>:

I have this code for a tool that copies files from one directory to another:

parser = argparse.ArgumentParser()
parser.add_argument('src_dir')
parser.add_argument('dest_dir')
args = parser.parse_args()

It works fine on Unix, but on Windows, if the destination path ends with a backward slash, it seems that argparse parses the string as it would escape a double quote and returns the string with the double quote appended.

For example, calling the script:
(base) PS Z:\test> python.exe .\main.py -d Z:\tmp\test\DJI\ 'C:\unu doi\'
will create the destination path string: C:\unu doi"
The source path, even though it ends with the backslash as well, isn't modified by argparse.

I've worked around this issue by using this validation function for the arguments:

def is_valid_dir_path(string):
    """
    Checks if the path is a valid path

    :param string: The path that needs to be validated
    :return: The validated path
    """
    if sys.platform.startswith('win') and string.endswith('"'):
        string = string[:-1]
    if os.path.isdir(string):
        return string
    else:
        raise NotADirectoryError(string)

parser = argparse.ArgumentParser()
parser.add_argument('src_dir', type=is_valid_dir_path)
parser.add_argument('dest_dir', type=is_valid_dir_path)
args = parser.parse_args()

----------
messages: 363339
nosy: 888xray999
priority: normal
severity: normal
status: open
title: Argparse on Python 3.7.1 (Windows) appends double quotes to string if it ends with backward slash
type: behavior
versions: Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39845>
_______________________________________


More information about the New-bugs-announce mailing list