I want to accept a directory path as user input in an add_argument()
of ArgumentParser()
.
So far, I have written this:
import argparse parser = argparse.ArgumentParser() parser.add_argument('path', option = os.chdir(input("paste here path to biog.txt file:")), help= 'paste path to biog.txt file')
What would be the ideal solution to this problem?
One can ensure the path is a valid directory with something like: import argparse, os def dir_path(string): if os. path. isdir(string): return string else: raise NotADirectoryError(string) parser = argparse.
The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.
Using argparse is how you let the user of your program provide values for variables at runtime. It's a means of communication between the writer of a program and the user. That user might be your future self. 😃 Using argparse means the doesn't need to go into the code and make changes to the script.
One can ensure the path is a valid directory with something like:
import argparse, os def dir_path(string): if os.path.isdir(string): return string else: raise NotADirectoryError(string) parser = argparse.ArgumentParser() parser.add_argument('--path', type=dir_path) # ...
Check is possible for files using os.path.isfile()
instead, or any of the two using os.path.exists()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With