In optparse I am using two flags and I want to get the next value after flag. My requirement is I may give any of the option or even both the options some times so I am using these options like flags. I am using parser.parse_args() to get the value but the problem is I am getting output including some brackets.
#!/usr/bin/python
import optparse
import sys
import os.path
parser = optparse.OptionParser()
parser.add_option('-p', action='store_true', default=False, dest='DEST1', help="Some info")
parser.add_option('-k', action='store_true', default=False, dest='DEST2', help="Some info")
options, infile = parser.parse_args()
print infile
O/P of file is
/myfile.py -p abc1
['abc1']
I need only file name as abc1
The second value in the tuple returned by parse_args()
is a list of remaining arguments. If you only want to process the first one, it's simple:
print infile[0]
By the way, argparse
is better than optparse
if you're using Python 2.7 or later. With argparse
you can declare your positional arguments explicitly (see the documentation). That means the parser can check that the user passed exactly one positional argument (for example), and also adds it to the --help
output.