2

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.

4

1 回答 1

2

您可以通过设置参数的默认属性来解决此问题。

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

然后做你的检查。这样,您只有一个函数来检查是否有多个 *.al 文件或没有参数是否被省略。

例如,这可以通过以下方式完成:

args =  parser.parse_args()
if isinstance(args.alphabet,types.ListType):
    if len(args.alphabet) != 1:
        parser.error("There must be exactly one alphabet in the directory")
    else:
        args.alphabet = open(args.alphabet[0])

这样,如果指定了字母文件或当前工作目录中只有一个字母文件,则 args.alphabet 将保存一个打开的文件,但如果 cwd 中有更多或没有字母文件,则会引发错误。

注意:因为如果-al参数被省略,我们会得到一个列表,argparse.FileType('r')不会打开任何文件。您还必须省略nargs=1,因为这将创建一个列表,其中包含一个打开的文件,即-al参数中指定的用户。省略此属性将为我们提供用户指定的原始打开文件。

编辑:你将不得不import types.

于 2013-08-16T14:11:35.107 回答