Home > Software design >  Parse path as argument in python script and how to type the path in the cmd window
Parse path as argument in python script and how to type the path in the cmd window

Time:12-14

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??

CodePudding user response:

Seems to work fine, and there are no errors in your code. How are you calling your script?

I'm guessing you are not calling it with any arguments, hence it is printing out None. If your script is called script.py, you would call it with an argument as follows:

python3 script.py -f hello prints out hello correctly.

If you have a #! /usr/bin/env python3 at the top of your script and make it executable, you can call it directly as ./script.py -f hello

CodePudding user response:

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/
Downloads

On 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

  • Related