将 Pytest 作为子进程调用

Call Pytest as a Subprocess

我想从 python 函数调用 pytest。我能够让它与 os.system 一起工作。我想使用子进程来检索 pytest 输出。

cmd = ["pytest", "-s", debug, "DeviceTests/{0}".format(test_name), "--device_id {0}".format(device_address), "--firmware_version {0}".format(firmware_version)]
print(cmd)
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)

子进程执行 运行 但告诉我有错误。我的 pytest 需要两个 CLI 选项。 运行 我被告知两个 CLI 选项不存在的子进程。

这是我的命令和错误。

Running Test DisioOnBACnetTest
['pytest', '-s', '--disable-pytest-warnings', 'DeviceTests/DisioOnBACnetTest', '--device_id 9101', '--firmware_version 0.1.1']
b''
b'ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]\npytest: error: the following arguments are required: --device_id, --firmware_version\n\n'

如您所见,我正在发送 device_id 和 firmware_version,但是子进程没有正确地将它们发送到 pytest。

您需要正确分隔参数。

这个:

"--device_id {0}".format(device_address), "--firmware_version {0}".format(firmware_version)

应该是

"--device_id", "{0}".format(device_address), "--firmware_version", "{0}".format(firmware_version)