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

标签 python command-line

我想使用这样的程序:

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 读取 FILE 类型,但是如果我将 -f 放在两者中,则会出现冲突错误。
关于如何继续的任何建议?
谢谢!

最佳答案

根据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')

关于Python:使用 OptionParser 从命令行获取 2 个文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38372627/

相关文章:

linux - 在 bash 中依次运行多个脚本

powershell - Visual Studio Code/powershell 命令 History up key

python - nose 在不运行它们的情况下获取测试列表

python - 如何为 "label for"设置正确的 xpath

python - 与字符串字符作斗争

python - 在反向代理后面添加前缀 url_for()

mysql - 如何知道命令行MySQL数据库导入是否崩溃?

windows - Windows XP下检测是否以管理员权限运行

python - 两个Python venv环境之间的连接在哪里

java - 在eclipse中,如何调用从控制台读取的函数?