python - 在一个 Windows 命令提示符下依次运行多个程序?

标签 python windows eclipse console subprocess

我需要一个接一个地运行多个程序,它们每个都在控制台窗口中运行。 我希望控制台窗口可见,但是为每个程序创建了一个新窗口。这很烦人,因为在 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/

相关文章:

Python/python3 在命令提示符下执行,但运行不正确

java - 无法启动 jBoss AS 7.1

java - 使用 Eclipse 风格的 Maven2 组织导入?

eclipse - 在 Eclipse 中,我可以为特定文件类型覆盖 "spaces for tabs"吗?

python - 'module' 对象没有属性 'SortedDict' Django Tastypie 错误

python - 使用 pymongo 与使用 pandas 进行聚合/分组

python - 带有不应相加的文本项的 Pandas groupby

Python 脚本使用 while 循环来不断更新作业脚本并多处理队列中的任务

windows - 我应该使用哪个版本的 MSXML?

php - 在新命令提示符下执行命令