【发布时间】:2013-08-18 22:05:16
【问题描述】:
我有一个输入文件的参数,并且很容易用 argparse 处理它
parser.add_argument( '-al', nargs = 1, type = argparse.FileType( 'r' ),
dest = 'alphabet' )
此参数是可选的,但如果省略,我仍然需要通过搜索当前目录来获取此输入文件。如果有多个 .al 扩展名的文件或没有文件,我将引发错误,否则打开我找到的文件。
#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' )
是否可以使用 argparse 执行此操作,可能使用默认或操作参数。 如果我在解析参数之前进行搜索并且存在异常情况,我仍然无法引发它,因为所需的文件可能由命令行参数提供。如果解析器不满足所需的参数,我想执行操作,但无法找到如何使用 argparse 执行操作。
【问题讨论】:
标签: python file default argparse optional-arguments