Tips and Tricks - Argparse: Convert Input to Absolute Path

Suppose you created a command-line interface using Python's argparse module and want to convert incoming paths directly to absolute ones. Thanks to the nature of argparse, this is pretty easy!

When adding a new argument to an ArgumentParser, you can specify the type of the argument. To convert the input to a regular pathlib.Path object, simply provide pathlib.Path to the type parameter:

import argparse
import pathlib

parser = argparse.ArgumentParser(description="Simple Parser")
parser.add_argument(
    dest="path",
    type=pathlib.Path,
)

Fortunately, you can supply any callable to the type parameter. To convert the supplied path to an absolute one, simply use a lambda-function:

import argparse
import pathlib

parser = argparse.ArgumentParser(description="Simple Parser")
parser.add_argument(
    dest="path",
    type=lambda p: pathlib.Path(p).absolute(),
)

Groups: standard library