使用Python在同一进程中运行三个命令

我需要在Win32上运行这三个命令以进行性能分析/代码覆盖率报告.

vsperfcmd /start:coverage /output:run.coverage
helloclass
vsperfcmd /shutdown

我不能一个地运行一个命令,因为应该在vsperfcmd的相同进程中分析helloclass可执行文件.

我想到的是制作一个批处理文件来运行这三个命令,并在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)

解决方法:

有趣的问题.

一种方法是运行命令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个调用都是不同的子进程.

上一篇:ubuntu ros问题


下一篇:vscode分别在ubuntu和windows下C\C++的配置文件。