Reputation: 1039
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?
Upvotes: 51
Views: 94833
Reputation: 1465
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()
Upvotes: 34
Reputation: 1675
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()
.
Upvotes: 61
Reputation: 675
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
Upvotes: 10