Search code examples
pythonargparsefilepath

Parse path as argument in python script and how to type the path in the cmd window


This part of the code always returns None

import argparse
from pathlib import Path


parser = argparse.ArgumentParser()
parser.add_argument('-f', "--file_path", type=Path)

p = parser.parse_args()
print(p.file_path)

I need to understand why this is happening. How could I solve it and how to correctly type a path in the cmd window?


Solution

  • Works as expected

    I saved your given script as SO_argparse_Path.py and run it with python3 and the argument -f Downloads/. See how it prints Downloads as expected folder:

    $ python3 SO_argparse_Path.py -f Downloads/
    

    which should print:

    Downloads

    On Windows you could run the script similarly in CMD.exe, e.g. with C:\:

    python SO_argparse_Path.py -f C:\ 
    

    which should print:

    C:\

    Paths with spaces inside should be wrapped inside doouble-quotes, see Handle spaces in argparse input

    About argument types

    From the docs of argparse on parameter type:

    The argument to type can be any callable that accepts a single string. If the function raises ArgumentTypeError, TypeError, or ValueError, the exception is caught and a nicely formatted error message is displayed. No other exception types are handled.

    (emphasis mine), also see the examples for built-in types there like: parser.add_argument('datapath', type=pathlib.Path)

    For a custom argument-handler see: path to a directory as argparse argument