python argparse, search for specific file if option is omitted -


i have argument input file , easy handle argparse

parser.add_argument( '-al', nargs = 1, type = argparse.filetype( 'r' ),                      dest = 'alphabet' ) 

this parameter optional if omitted still need input file searching current directory. , if there more 1 or none file .al extensions raise error, otherwise open file found.

#if no alphabet .al file in current directory if( args.alphabet == none ):     alfiles = [ f f in os.listdir( '.' )                  if os.path.isfile( f ) , f.endswith( '.al' ) ]      #there should 1 file .al extension     if( len( alfiles ) != 1 ):             sys.exit( 'error: no alphabet file provided , '                     'there more 1 or no .al file in current directory, '                     'which leads ambiguity' )      args.alphabet = open( alfiles[0], 'r' ) 

is there anyway perform argparse, default or action parameters maybe. if search before parsing arguments , there exception situation still can not raise because needed file may provided command line arguments. thought of performing action if parser did not meet needed parameter, can not find out how argparse.

you can fix setting default attribute argument.

parser = argparse.argumentparser() parser.add_argument('-al',                     type = argparse.filetype('r'),                     default = [ f f in os.listdir( '.' )                                 if os.path.isfile( f ) , f.endswith( '.al' )],                     dest = 'alphabet' ) 

and afterwards checking. way have 1 function checking if there more 1 or none *.al files whether argument omitted or not.

this could, example, accomplished this:

args =  parser.parse_args() if isinstance(args.alphabet,types.listtype):     if len(args.alphabet) != 1:         parser.error("there must 1 alphabet in directory")     else:         args.alphabet = open(args.alphabet[0]) 

this way args.alphabet hold open file if there alphabet file specified or there 1 alphabet file in current working directory, raise error if there more or none in cwd.

note: because list if -al argument omitted, argparse.filetype('r') not open file. have omit nargs=1 since create list containing 1 opened file, user specified in -al argument. omitting attribute give raw open file, user specified.

edit: have import types.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -