我已经阅读了很多关于此的帖子并尝试了所有方法,但不知何故我无法将命令行参数传递给 pyCharm 中的 python 代码。我已经做了以下工作
A)请参阅附加的第一张图片,当我运行代码时出现此错误
C:\Automation\myTest\venv\Scripts\python.exe -s C:/Automation/myTest/myTest.py ABC XYZ
======================================================================
ERROR: ABC (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'ABC'
======================================================================
ERROR: XYZ (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'XYZ'
我尝试了与附图中所示相同的方法,但没有 -s 选项
C:\Automation\myTest\venv\Scripts\python.exe C:/Automation/myTest/myTest.py ABC XYZ
======================================================================
ERROR: ABC (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'ABC'
======================================================================
ERROR: XYZ (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'XYZ'
代码
class Ktests(unittest.TestCase):
@classmethod
def setUpClass(self):
super(Ktests, self).setUpClass()
self.prepareInitalData(self)
@classmethod
def tearDownClass(self):
print('Tear Down')
super(Ktests, self).tearDownClass()
def prepareInitalData(self):
do stuff
def otherMethod(self):
do Other stuff
def test(self):
self.suites()
def suites(self):
runTest1()
....
if __name__ == '__main__':
unittest.main()
最佳答案
如果不知道 myTest.py
中的内容,这只是猜测,但如果您在文件运行时调用 unittest
或测试运行程序,然后参数被解释为要运行的测试模块。换句话说,unittest
正在寻找名为 ABC
和 XYZ
的 Python 测试模块。如果 ABC.py
和 XYZ.py
不存在,您将得到您所看到的那种错误。
如果您想要拥有自己的参数,除了 unittest
的期望之外,您还可以通过直接传入参数来修改对 main()
的调用。例如,如果您想自己使用第一个参数(在程序名称之后),并将其余部分传递给 unittest
:
if __name__ == '__main__':
arg1, arg2 = sys.argv[1:3]
unittest.main(argv=sys.argv[3:])
这会将第一个参数分配给您可以使用的变量,然后将其他任何参数传递给 unittest
。因此,您可以在原来的问题中调用电话:
python myTest.py ABC XYZ
或者您可以这样做,并运行特定的测试:
python myTest.py ABC XYZ path.to.test.module
https://docs.python.org/3/library/unittest.html#unittest.main
关于python - pyCharm 命令行参数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57716646/