I have an argument for input file and its easy to handle it with argparse
parser.add_argument( '-al', nargs = 1, type = argparse.FileType( 'r' ),
dest = 'alphabet' )
This parameter is optional but if it is omitted I still need to get this input file by searching current directory. And if there is more than one or none file with .al extensions I will raise the error, otherwise open file I found.
#if no alphabet look for .al file in current directory
if( args.alphabet == None ):
AlFiles = [ f for f in os.listdir( '.' )
if os.path.isfile( f ) and f.endswith( '.al' ) ]
#there should be one file with .al extension
if( len( AlFiles ) != 1 ):
sys.exit( 'error: no alphabet file provided and '
'there are more than one or no .al file in current directory, '
'which leads to ambiguity' )
args.alphabet = open( AlFiles[0], 'r' )
Is there anyway to perform this with argparse, with default or action parameters maybe. If I do the search before parsing arguments and there are an exception situation I still can not raise it because needed file may be provided by command line arguments. I thought of performing action if parser did not meet needed parameter, but can not find out how to do it with argparse.