1

How to add a mandatory option to the parser with prefix -i or --input to specify the input file to the script?

The provided value should be placed into the infile variable

1 Answer 1

1

Distilling from the documentation, a minimalistic answer would be

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

Be aware that if the specified file does not exist, the parser will throw an IOError. removing the type=file parameter will default to reading a string and will let you handle the file operations on the parameter later on.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.