python,unittest:有没有办法将命令行选项传递给应用程序 [英] python, unittest: is there a way to pass command line options to the app
问题描述
我有一个导入 unittest 的模块并有一些 TestCase.我想接受一些命令行选项(例如下面的数据文件的名称),但是当我尝试传递选项时,我收到消息 option -i not识别
.是否可以让 unittest
+ 为应用程序提供选项(注意:我正在使用 optparse
来处理选项)?谢谢.
I have a module that imports unittest and has some TestCases. I would like
to accept some command-line options (for example below, the name of a data file),
but when I try to pass the option I get the message option -i not recognized
. Is it possible to have unittest
+ provide options to the app (note: I'm using optparse
to handle the options)? Thanks.
$ python test_app_data.py -i data_1.txt
option -i not recognized
======================
=====================
后续:这是建议解决方案的实施:
follow-up: this is an implementation of the suggested solution:
import cfg_master #has the optparse option-handling code
...
if __name__ == '__main__':
#add you app's options here...
options_tpl = ('-i', '--in_dir', '-o', '--out_dir')
del_lst = []
for i,option in enumerate(sys.argv):
if option in options_tpl:
del_lst.append(i)
del_lst.append(i+1)
del_lst.reverse()
for i in del_lst:
del sys.argv[i]
unittest.main()
推荐答案
以 Alex 的回答为基础,使用 argparse
:
Building on Alex's answer, it's actually pretty easy to do using argparse
:
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--input', default='My Input')
parser.add_argument('filename', default='some_file.txt')
parser.add_argument('unittest_args', nargs='*')
args = parser.parse_args()
# TODO: Go do something with args.input and args.filename
# Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone)
sys.argv[1:] = args.unittest_args
unittest.main()
我还没有测试您可以传递给 unittest 的所有标志以查看它们是否有效,但传递测试名称确实有效,例如:
I haven't tested all of the flags you can pass into unittest to see if they work or not, but passing test names in does work, e.g.:
python test.py --input=foo data.txt MyTest
使用 foo
和 data.txt
运行 MyTest.
Runs MyTest with foo
and data.txt
.
这篇关于python,unittest:有没有办法将命令行选项传递给应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!