【问题标题】:argparse and unittest pythonargparse 和 unittest python
【发布时间】:2013-12-14 10:56:10
【问题描述】:

我正在使用argparse 来处理命令行参数。代码工作正常。但是,一旦我在主目录中添加 unittest.main(),它就不起作用了。

我得到:

I am here 
option -i not recognized
Usage: testing.py [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output
  -f, --failfast   Stop on first failure
  -c, --catch      Catch control-C and display results
  -b, --buffer     Buffer stdout and stderr during test runs

Examples:
  testing.py                               - run default set of tests
  testing.py MyTestSuite                   - run suite 'MyTestSuite'
  testing.py MyTestCase.testSomething      - run MyTestCase.testSomething
  testing.py MyTestCase                    - run all 'test*' test methods
                                               in MyTestCase

我是这样做的:

if __name__ == "__main__":
    print "I am here"
    unittest.main()

【问题讨论】:

  • 没有选项-i 所以错误是正确的。如何调用脚本?
  • 我这样调用脚本:python testing.py -isVerbose True
  • 那么这是一个问题:您应该将其称为python testing.py --verbose,因为您没有声明名为isVerbose的选项。
  • 没有。我已经定义了 isVerbose。 args = parser.parse_args() isVerbose=args.isVerbose

标签: python argparse


【解决方案1】:

使用

runner = unittest.TextTestRunner()
itersuite = unittest.TestLoader().loadTestsFromTestCase(MyTestClass)
runner.run(itersuite)

代替:

unittest.main()

【讨论】:

  • 太棒了,它现在可以工作了。不明白为什么 unittest.main() 失败了。
  • unittest.main() 似乎查看了传递给主代码的任何参数,因此它试图解析您的自定义参数,当然,它不能。
【解决方案2】:

如果您不需要任何参数,请使用

unittest.main(argv=[''])

【讨论】:

    猜你喜欢
    • 2019-08-23
    • 2014-02-01
    • 2016-06-19
    • 2013-08-21
    • 2016-05-23
    • 2016-12-25
    • 2016-05-18
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多