python - pyCharm 命令行参数不起作用

标签 python pycharm

我已经阅读了很多关于此的帖子并尝试了所有方法,但不知何故我无法将命令行参数传递给 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()

enter image description here

最佳答案

如果不知道 myTest.py 中的内容,这只是猜测,但如果您在文件运行时调用 unittest 或测试运行程序,然后参数被解释为要运行的测试模块。换句话说,unittest 正在寻找名为 ABCXYZ 的 Python 测试模块。如果 ABC.pyXYZ.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/

相关文章:

python - Flask-WTForms:如何检查是否需要一个字段?

python - 将 csv 文件 append 到 Python 2.7.3 中的一个空列表中 - 返回一个空列表

javascript - 为什么在 JavaScript 中收到我的个人推文 ID 号时,最后几位数字变为 "0"?

python - 我如何在 Eclipse 中调试 openerp 代码

pycharm - 如何使PyCharm在运行时警告中断?

python - 有没有办法用 PyCharm 捕获单元测试异常?

python - 使用 matplotlib 在 sankey 图中连接两个以上的系统让我错位

ipython - PyCharm:如何在 ipython 交互式控制台中进行事后调试?

python - PyCharm 中 numpy 的问题

github - 无法将 Github 与 Pycharm 集成