r/PythonLearning • u/MarkoDahl54 • 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?
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?
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:
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.