Python:使用OptionPars从命令行获取2个文件名

2024-03-28 09:23:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用这样一个程序:

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

其中f1、f2是文件名。
我有以下代码:

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')
....
....  

我在文档中读到-f读取文件类型,但如果将-f同时放在这两种类型中,则会出现冲突错误。
对如何进行有什么建议吗?
谢谢您!你知道吗


Tags: csvpy程序adddefaulthelpfiledest
1条回答
网友
1楼 · 发布于 2024-03-28 09:23:32

根据documentation,optparse不支持带有单连字符(-)的多个字母。你知道吗

Some option syntaxes that the world has seen include:

  • a hyphen followed by a few letters, e.g. -pf (this is not the same as multiple options merged into a single argument)
  • a hyphen followed by a whole word, e.g. -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, e.g. +f, +rgb
  • a slash followed by a letter, or a few letters, or a word, e.g. /f, /file

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

您应该将选项键更改为-f1-a-f2-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')

相关问题 更多 >