我需要一个接一个地运行多个程序,它们每个都在控制台窗口中运行。 我希望控制台窗口可见,但是为每个程序创建了一个新窗口。这很烦人,因为在 Eclipse 中工作时,每个窗口都在另一个窗口关闭的新位置打开并窃取焦点。
这是我使用的初始代码:
def runCommand( self, cmd, instream=None, outstream=None, errstream=None ):
proc = subprocess.Popen( cmd, stdin=instream, stdout=outstream, stderr=errstream )
while True:
retcode = proc.poll()
if retcode == None:
if mAbortBuild:
proc.terminate()
return False
else:
time.sleep(1)
else:
if retcode == 0:
return True
else:
return False
在调用 subprocess.Popen 然后调用 proc.stdin.write( b'program.exe\r\n' ) 时,我切换为使用“cmd”打开命令提示符。 这似乎解决了一个命令窗口的问题,但现在我不知道第一个程序何时完成,我可以启动第二个。我想在运行第二个程序之前停止并查询第一个程序的日志文件。
关于如何实现这一目标的任何提示?我还没有找到另一种在一个窗口中运行程序的选项吗?
最佳答案
由于您使用的是 Windows,因此您可以创建一个批处理文件,列出您要运行的每个程序,这些程序都将在一个控制台窗口中执行。由于它是一个批处理脚本,您可以执行诸如在其中放入条件语句之类的操作,如示例中所示。
import os
import subprocess
import textwrap
# create a batch file with some commands in it
batch_filename = 'commands.bat'
with open(batch_filename, "wt") as batchfile:
batchfile.write(textwrap.dedent("""
python hello.py
if errorlevel 1 (
@echo non-zero exit code: %errorlevel% - terminating
exit
)
time /t
date /t
"""))
# execute the batch file as a separate process and echo its output
kwargs = dict(stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True)
with subprocess.Popen(batch_filename, **kwargs).stdout as output:
for line in output:
print line,
try: os.remove(batch_filename) # clean up
except os.error: pass
关于python - 在一个 Windows 命令提示符下依次运行多个程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4415134/