Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

path to a directory as argparse argument

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?

like image 818
user3698773 Avatar asked Aug 08 '16 16:08

user3698773


People also ask

How do I give path to Argparse?

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.

What is Argparse ArgumentParser ()?

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.

What is ArgumentParser in Python?

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.


1 Answers

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

like image 165
Joseph Marinier Avatar answered Oct 05 '22 20:10

Joseph Marinier