3

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
Flimm
  • 136,138
  • 45
  • 251
  • 267
frankV
  • 5,353
  • 8
  • 33
  • 46
  • can you show your code? This should be a pretty easy thing to do ... Maybe seeing your code will help us to understand what you're having a hard time with. – mgilson Mar 12 '13 at 17:37
  • I don't have anything for passing the directory right now. I've tried various options but have gotten nowhere worth keeping. – frankV Mar 12 '13 at 17:40
  • If you do want type checking, see: https://stackoverflow.com/q/11415570/247696 – Flimm Nov 06 '19 at 09:34

1 Answers1

4

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
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • can I just use `'directory'` as the variable holding my path from that point on? – frankV Mar 12 '13 at 17:46
  • @frankV -- It'll be `args.directory`, but you can easily just do `directory = args.directory` if you want to. – mgilson Mar 12 '13 at 17:47