谁能发现为什么以下脚本不打印传递的论点?

import sys, getopt

def usage():
    print 'Unknown arguments'

def main(argv):
    try:
        opts, args = getopt.getopt(argv,'fdmse:d',['files=','data-source=','mode=','start','end'])

    except getopt.GetoptError:
        usage()
        sys.exit(999)

    for opt, arg in opts:
        # print opt,arg 
        if opt in('-f','--files'):
            print 'files: ', arg  #

if __name__ == "__main__":
    main(sys.argv[1:])

当我在命令行中运行脚本并通过参数 -f=dummy.csv, usage() 似乎被调用了 - 为什么?

顺便说一句,我发现程序流的逻辑有点奇怪(我从 这里)。通常,我会认为逻辑将在Try分支中实现,然后在此之后进行例外处理程序。

这是否(如上面的代码中粘贴)编写尝试/捕获块的“ Pythonic”方法?

有帮助吗?

解决方案

通常,我会认为逻辑将在TRY分支中实现

“一般”?通常是什么意思?

该程序应该做什么?什么例外有意义?该程序对异常有什么作用。

没有“正常”。除了正常的分配语句或正常函数定义之外,任何多的内容。

您的程序做有意义的事情来实现所需的最终状态。没有“正常”。

其他提示

你得到答案了吗?

调试Python例外的一种方法是将代码移出Try Block(临时调试)。您将获得完整的痕迹。

当然,另一种方法是减少测试案例。在这里,我已经将问题减少到三行,并尝试了 @s.lott暗示的解决方案(在getopts呼叫中使用'f:'),并最终显示出一些不同的测试数据的调用方式:

$ cat x1.py
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:],'fdmse:d',['files=','data-source=','mode=','start','end'])
print "opts=", opts, "args=", args

$ python x1.py -f=dummy.csv argblah
Traceback (most recent call last):
  File "x1.py", line 2, in <module>
    opts, args = getopt.getopt(sys.argv[1:],'fdmse:d',['files=','data-source=','mode=','start','end'])
  File "/usr/lib/python2.6/getopt.py", line 91, in getopt
    opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
  File "/usr/lib/python2.6/getopt.py", line 191, in do_shorts
    if short_has_arg(opt, shortopts):
  File "/usr/lib/python2.6/getopt.py", line 207, in short_has_arg
    raise GetoptError('option -%s not recognized' % opt, opt)
getopt.GetoptError: option -= not recognized

$ sed 's/fdm/f:dm/' <x1.py >x2.py

$ diff x1.py x2.py
2c2
< opts, args = getopt.getopt(sys.argv[1:],'fdmse:d',['files=','data-source=','mode=','start','end'])
---
> opts, args = getopt.getopt(sys.argv[1:],'f:dmse:d',['files=','data-source=','mode=','start','end'])

$ python x2.py -f=dummy.csv argblah
opts= [('-f', '=dummy.csv')] args= ['argblah']

$ python x1.py -f dummy.csv argblah
opts= [('-f', '')] args= ['dummy.csv', 'argblah']

导入和使用argparse而不是getopt。它更容易使用,并且几乎拥有从命令行中运行的所有所需的一切。

一个例子,

    parser = argparse.ArgumentParser(
        description='Description of what the module does when run.')
    parser.add_argument("-o", "--output", help='Path of log file.')
    args = parser.parse_args()

那样容易。当然,您需要在文件的顶部导入ArgParse才能工作。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top