我需要运行这三个命令来在 Win32 上进行分析/代码覆盖率报告。
vsperfcmd /start:coverage /output:run.coverage
helloclass
vsperfcmd /shutdown
我不能一个一个地运行一个命令,因为 helloclass 可执行文件应该在 vsperfcmd 的同一进程中进行分析。
我想到的是制作一个批处理文件来运行这三个命令,并在 Python 中运行该批处理文件。但是,我认为 python 应该有一种方法来执行启动 shell 和运行命令的等效操作。
- 问:如何在 Python 中运行同一进程中的命令?
- 问:或者,我如何在 Python 中启动命令 shell 并运行命令?
解决了
import subprocess
cmdline = ["cmd", "/q", "/k", "echo off"]
cmd = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
batch = b"""\
rem vsinstr -coverage helloclass.exe /exclude:std::*
vsperfcmd /start:coverage /output:run.coverage
helloclass
vsperfcmd /shutdown
exit
"""
cmd.stdin.write(batch)
cmd.stdin.flush() # Must include this to ensure data is passed to child process
result = cmd.stdout.read()
print(result)