52

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?

4
  • add_argument does not take a option parameter. Is this path name supposed to come from the command line? Is it ok to change path after parsing? Commented Aug 8, 2016 at 17:49
  • It might be useful to note that argparse seems to have severe limitation: the methods that add arguments do not check for valid paths. Seems like core functionality to me, but the thing is still very useful. In the meantime you'd need to add your own logic to check each path. Some people have written an additional class to achieve this: gist.github.com/brantfaircloth/1443543 Commented May 17, 2017 at 5:55
  • Also see stackoverflow.com/questions/11415570/…. Commented May 17, 2017 at 6:08
  • 1
    Possible duplicate of directory path types with argparse Commented Nov 6, 2019 at 9:33

3 Answers 3

62

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().

Sign up to request clarification or add additional context in comments.

Comments

35

Argument Parser(argparse) Examples : Different type of arguments with custom handlers added. For PATH you can pass "-path" followed by path value as argument

import os import argparse from datetime import datetime def parse_arguments(): parser = argparse.ArgumentParser(description='Process command line arguments.') parser.add_argument('-path', type=dir_path) parser.add_argument('-e', '--yearly', nargs = '*', help='yearly date', type=date_year) parser.add_argument('-a', '--monthly', nargs = '*',help='monthly date', type=date_month) return parser.parse_args() def dir_path(path): if os.path.isdir(path): return path else: raise argparse.ArgumentTypeError(f"readable_dir:{path} is not a valid path") def date_year(date): if not date: return try: return datetime.strptime(date, '%Y') except ValueError: raise argparse.ArgumentTypeError(f"Given Date({date}) not valid") def date_month(date): if not date: return try: return datetime.strptime(date, '%Y/%m') except ValueError: raise argparse.ArgumentTypeError(f"Given Date({date}) not valid") def main(): parsed_args = parse_arguments() if __name__ == "__main__": main() 

1 Comment

argparse.ArgumentTypeError is much better for clear error messages. Thanks!
10

You can use something like:

import argparse, os parser = argparse.ArgumentParser() parser.add_argument('--path', help= 'paste path to biog.txt file') args = parser.parse_args() os.chdir(args.path) # to change directory to argument passed for '--path' print os.getcwd() 

Pass the directory path as an argument to --path while running your script. Also, check the official document for correct usage of argparse: https://docs.python.org/2/howto/argparse.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.