简体   繁体   中英

Python: Get 2 filenames from command line using OptionParser

I want to use a program like this:

python myprg.py -f1 t1.txt -f2 t.csv

where f1, f2 are filenames.
I have the following code:

from optparse import OptionParser
def main():
    optparser = OptionParser()
    optparser.add_option('-f1', '--inputFile1',
                         dest='input1',
                         help='file to be checked',
                         default=None)
    optparser.add_option('-f2', '--inputFile2',
                         dest='input2',
                         help='basis csv file',
                         default='defaut.csv')
....
....  

I read in documentation that -f reads FILE types, but if I put -f in both, it gives an error of conflict.
Any suggestions on how to proceed?
Thank you!

According to documentation , optparse does not support multiple letters with single hyphen (-).

Some option syntaxes that the world has seen include:

  • a hyphen followed by a few letters, eg -pf (this is not the same as multiple options merged into a single argument)
  • a hyphen followed by a whole word, eg -file (this is technically equivalent to the previous syntax, but they aren't usually seen in
    the same program)
  • a plus sign followed by a single letter, or a few letters, or a word, eg +f, +rgb
  • a slash followed by a letter, or a few letters, or a word, eg /f, /file

These option syntaxes are not supported by optparse, and they never will be.

You should change option keys something like that -f1 to -a , -f2 to -b .

python myprg.py -a t1.txt -b t.csv 



optparser.add_option('-a', '--inputFile1',
                         dest='input1',
                         help='file to be checked',
                         default=None)
optparser.add_option('-b', '--inputFile2',
                         dest='input2',
                         help='basis csv file',
                         default='defaut.csv')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM