我需要在Win32上运行这三个命令进行性能分析/代码覆盖率报告。
vsperfcmd /start:coverage /output:run.coverage
helloclass
vsperfcmd /shutdown
我无法逐个运行一个命令,因为应该在vsperfcmd的同一进程中分析helloclass可执行文件。
我想到的是制作一个批处理文件来运行这三个命令,并在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)
答案 0 :(得分:6)
有趣的问题。
一种方法是运行命令shell,然后通过stdin
将命令传递给它(示例使用Python 3,对于Python 2,您可以跳过decode()
调用)。请注意,命令shell调用设置为禁止除显式输出写入stdout之外的所有内容。
>>> import subprocess
>>> cmdline = ["cmd", "/q", "/k", "echo off"]
>>> cmd = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> batch = b"""\
... set TEST_VAR=Hello World
... set TEST_VAR
... echo %TEST_VAR%
... exit
... """
>>> cmd.stdin.write(batch)
59
>>> cmd.stdin.flush() # Must include this to ensure data is passed to child process
>>> result = cmd.stdout.read()
>>> print(result.decode())
TEST_VAR=Hello World
Hello World
将其与subprocess.call
:
>>> subprocess.call(["set", "TEST_VAR=Hello World"], shell=True)
0
>>> subprocess.call(["set", "TEST_VAR"], shell=True)
Environment variable TEST_VAR not defined
1
>>> subprocess.call(["echo", "%TEST_VAR%"], shell=True)
%TEST_VAR%
0
后两个调用无法看到第一个调用所设置的环境,因为所有3个调用都是不同的子进程。
答案 1 :(得分:1)