4

谁能发现为什么以下脚本没有打印传递的参数?

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 分支中实现,然后是异常处理程序。

这是(如粘贴在上面的代码中)编写 try/catch 块的“Pythonic”方式吗?

4

3 回答 3

2

你得到你的答案了吗?

调试 python 异常的一种方法是将代码移出 try 块(或临时复制以进行调试)。你会得到一个完整的跟踪。

当然,另一种方法是减少测试用例。在这里,我将问题减少到三行,并尝试了@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']
于 2010-11-29T23:42:46.997 回答
1

通常我会认为逻辑会在try分支中实现

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

程序应该做什么?哪些例外有意义?程序如何响应异常。

没有“正常”。不仅仅是普通的赋值语句或普通的函数定义。

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

于 2010-10-14T15:33:15.153 回答
0

导入并使用 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 才能使其正常工作。

于 2015-02-16T04:34:29.763 回答