2016-11-25 1 views
-1

접두사 -i 또는 --input을 사용하여 구문 분석기에 필수 옵션을 추가하여 스크립트의 입력 파일을 지정하는 방법은 무엇입니까?python argparse 필수 입력 파일 인수가

제공되는 값은 문서에서 증류 INFILE 변수

답변

0

에 배치해야하는 최소한의 대답은

import argparse 

#Create the parser 
parser = argparse.ArgumentParser(description='Does some stuff with an input file.') 

#add the argument 
parser.add_argument('-i', '--input', dest='infile', type=file, required=True, 
       metavar='INPUT_FILE', help='The input file to the script.') 

#parse and assign to the variable 
args = parser.parse_args() 
infile=args.infile 

지정된 파일이 존재하지 않는 경우, 파서가 던질 것이라는 점을주의 할 것 IOError. type = file 매개 변수를 제거하면 기본적으로 문자열을 읽게되고 나중에 매개 변수에 대한 파일 작업을 처리 할 수있게됩니다.

관련 문제