from argparse import ArgumentParser
class MainClass:
@classmethod
def main(cls):
print("[Start of Main]")
# initialize argument parser
my_parser = ArgumentParser()
my_parser.add_argument("-i", help="input directory", type=str)
my_parser.add_argument("-o", help="output directory", type=str)
my_group = my_parser.add_mutually_exclusive_group()
my_group.add_argument("--txt", help="output as .txt files")
my_group.add_argument("--rtf", help="output as .rtf files")
# parse the argument
args = my_parser.parse_args()
if args.i is None:
print("INPUT: current directory")
else:
print("INPUT: specific directory = " + args.i)
if args.o is None:
print("OUTPUT: current directory")
else:
print("OUTPUT: specific directory = " + args.o)
if args.txt is not None:
print(".txt output")
if args.rtf is not None:
print(".rtf output")
print("[End of Main]")
if __name__ == '__main__':
MainClass.main()
Output
C:\Users\pc\source>python argparse_test.py --txt
[Start of Main]
usage: argparse_test.py [-h] [-i I] [-o O] [--txt TXT | --rtf RTF]
argparse_test.py: error: argument --txt: expected one argument
C:\Users\pc\source>
In this source code --txt
and --rtf
are not expected to receive any argument, and they should also be mutually exclusive.
So, how can I fix this?
Edit (1):
my_group = my_parser.add_mutually_exclusive_group()
my_group.add_argument("--txt", help="output as .txt files", action='store_true')
my_group.add_argument("--rtf", help="output as .rtf files", action='store_true')
The above modification is making the program display both txt
and rtf
.
C:\Users\pc\source>python argparse_test.py --txt
[Start of Main]
INPUT: current directory
OUTPUT: current directory
.txt output
.rtf output
[End of Main]
C:\Users\pc\source>
Edit (2): testing True
/False
gives better result:
if args.txt is True:
print(".txt output")
if args.rtf is True:
print(".rtf output")
Output:
C:\Users\pc\source>python argparse_test.py --txt
[Start of Main]
Namespace(i=None, o=None, rtf=False, txt=True)
INPUT: current directory
OUTPUT: current directory
.txt output
[End of Main]
However, inputting --txt
and --rtf
at the same time gives an error:
C:\Users\pc\source>python argparse_test.py --txt --rtf
[Start of Main]
usage: argparse_test.py [-h] [-i I] [-o O] [--txt | --rtf]
argparse_test.py: error: argument --rtf: not allowed with argument --txt