I want to implement a python3 command line by argparse, which supports positional arguments and flag options.
For example:
usage: mycmd [-v] [-h] [-o] text
mycmd text print text
mycmd -h show help message and exit
mycmd -v show version info
mycmd -o text print text and dump text to file mycmd.txt
Here's my implementation:
import argparse
class MyCmd:
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument('text', help='print text') # mycmd text
self.parser.add_argument('-v', action='store_true', dest='version', help='show version info') # mycmd -v
self.parser.add_argument('-o', dest='output', help='print text and dump text to file mycmd.txt')
def parse(self):
return self.parser.parse_args()
def text(self, text):
print(text)
def version(self):
print('version info: mycmd-0.0.1')
def output(self, text):
print(text)
fp = open('mycmd.txt', 'w')
fp.write(text + '\n')
fp.close()
if __name__=='__main__':
mycmd = MyCmd()
(options, args) = mycmd.parse()
if options.text is not None:
mycmd.text(text)
elif options.version is not None:
mycmd.version()
elif options.output is not None:
mycmd.output(options.output)
When I test it with:
$ ./mycmd -v
Gives me error:
usage: mycmd [-h] [-o OUTPUT]
[-v]
text
mycmd: error: the following arguments are required: text
Why mycmd cannot consume mycmd -v ?
textargument.