Run multiple programs sequentially in one Windows command prompt?

后端 未结 2 1655
心在旅途
心在旅途 2020-11-27 22:30

I need to run multiple programs one after the other and they each run in a console window. I want the console window to be visible, but a new window is created for each prog

2条回答
  •  一向
    一向 (楼主)
    2020-11-27 23:17

    Since you're using Windows, you could just create a batch file listing each program you want to run which will all execute in a single console window. Since it's a batch script you can do things like put conditional statements in it as shown in the example.

    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
    

提交回复
热议问题