在我的主要代码中我有这个:
#comp.py
parser = ArgumentParser()
parser.add_argument("-n", dest="deg", default=100,type=int, help="setup value of deg")
parser.add_argument("-k", dest="k", default=25, type=float, help="setup value of k")
parser.add_argument("-l", dest="l", default=0, type=int, help="setup value of l")
args = parser.parse_args()
def afunc(x):
...
#do something with k, l, deg and the return the result
...
return result
和我的测试文件verify.py
:
#verify.py
import unittest
import comp
class TestFuncs(unittest.TestCase):
def test_afunc(self):
self.assertEqual(afunc(0), 0)
self.assertEqual(afunc(1), 0)
self.assertEqual(afunc(1), 1)
self.assertEqual(afunc(3.2), 1)
...
当我尝试运行 nosetests
来测试函数 afunc(...)
的结果时,我得到了这个错误:
machine:project user$ nosetests verify
usage: nosetests [-h] [-n DEG] [-k K] [-l L]
nosetests: error: unrecognized arguments: verify
如何解决这个问题?
最佳答案
好吧,我只是通过添加几行 if else 条件解决了这个问题。
这似乎是我的测试文件 (verify.py
) 无法管理 comp.py
中解析器部分的赋值。所以,我只是在下面添加一些条件来分配 deg
、k
、l
的值,以防 comp.py
不作为主函数运行。
#comp.py
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-n", dest="deg", default=100,type=int, help="setup value of deg")
parser.add_argument("-k", dest="k", default=25, type=float, help="setup value of k")
parser.add_argument("-l", dest="l", default=0, type=int, help="setup value of l")
args = parser.parse_args()
else:
deg=100
k=25
l=0
def afunc(x):
...
#do something with k, l, deg and the return the result
...
return result
关于python - 当我在 python 代码中使用 argparse 时无法运行 nosetests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24397258/