frankV
frankV

Reputation: 5513

Pass a directory with argparse (no type checking needed)

I've written a file crawler and I'm trying to expand it. I want to use argparse to handle settings for the script including passing the starting directory in at the command line.

Example: /var/some/directory/

I have gotten several other arguments to work but I'm unable to pass this directory in correctly. I don't care if it's preceded by a flag or not, (e.g -d /path/to/start/) but I need to make sure that at the very least, this is argument is used as it will be the only mandatory option for the script to run.

Code Sample:

parser = argparse.ArgumentParser(description='py pub crawler...')
parser.add_argument('-v', '--verbose', help='verbose output from crawler', action="store_true")
parser.add_argument('-d', '--dump', help='dumps and replaces existing dictionaries', action="store_true")
parser.add_argument('-f', '--fake', help='crawl only, nothing stored to DB', action="store_true")

args = parser.parse_args()

if args.verbose:
    verbose = True
if args.dump:
    dump = True
if args.fake:
    fake = True

Upvotes: 3

Views: 10044

Answers (1)

mgilson
mgilson

Reputation: 309861

Simply add:

parser.add_argument('directory',help='directory to use',action='store')

before your args = parser.parse_args() line. A simple test from the commandline shows that it does the right thing (printing args at the end of the script):

$ python test.py /foo/bar/baz
Namespace(directory='/foo/bar/baz', dump=False, fake=False, verbose=False)
$ python test.py
usage: test.py [-h] [-v] [-d] [-f] directory
test.py: error: too few arguments

Upvotes: 4

Related Questions