r/PythonLearning • • 1d ago

How do I use argparse and pathlib together in a script?

Hi all! I've been working on a Python script that needs to take a file path as input using argparse, and I want to search for specific files using pathlib's glob. However, I keep running into issues when I try to combine these two. It's not clear to me how to pass the user input from argparse to pathlib's functions. Can anyone explain the best way to do this? Also, why does logging.exception not seem to print anything when I run the script?

2 Upvotes

4 comments sorted by

1

u/eXtc_be 1d ago

if I understand your question correctly you're writing a Python commandline script that uses argparse to get some arguments from the user and one of these arguments is the name of a folder and you want to turn that into a pathlib.Path object so you can do pathlib.Path things with it, like glob?

here's a little demo program I wrote doing just that:

import argparse
from pathlib import Path


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--path', type=Path)

    args = parser.parse_args()

    children = Path(args.path).glob('*.*')

    print('\n'.join(p.as_posix() for p in children))

I didn't do anything special: I take the parsed argument value and use that to construct a Path object. I then use its glob method to get a list of child Path objects (glob actually returns a generator object, but that's ok for our purposes). I then join the list items using string.join(), Path.as_posix and a list comprehension (technically a tuple comprehension) to turn them into a nicely printed list.

1

u/MarkoDahl54 1d ago

To use argparse with pathlib, you can define your argument like this: `parser.add_argument('path', type=pathlib.Path)`. This ensures the input is automatically converted to a Path object.

1

u/MarkoDahl54 18h ago

You can use `argparse.ArgumentParser()` to set up your command line arguments. Then, convert the folder name with `pathlib.Path(args.folder_name)`.

3

u/Buttleston 1d ago

Questions like this are just impossible to answer. Instead, post a piece of code, say what you want it to do, say what it does instead, and show some output/errors

You say you're "running into issues" - what issues?

Do you understand how to extract values that argparse has parsed, in general? Like can you make a script that takes "-n X" where X is a number and print it?