43

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?

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
user3698773
  • 929
  • 2
  • 8
  • 15
  • `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? – hpaulj Aug 08 '16 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: https://gist.github.com/brantfaircloth/1443543 – Jonathan Komar May 17 '17 at 05:55
  • Also see http://stackoverflow.com/questions/11415570/directory-path-types-with-argparse. – Jonathan Komar May 17 '17 at 06:08
  • 1
    Possible duplicate of [directory path types with argparse](https://stackoverflow.com/questions/11415570/directory-path-types-with-argparse) – Flimm Nov 06 '19 at 09:33

3 Answers3

53

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

Joseph Marinier
  • 1,390
  • 12
  • 8
29

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()
Asad Manzoor
  • 1,355
  • 15
  • 18
9

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

Abhishek Balaji R
  • 665
  • 10
  • 25