Run multiple programs sequentially in one Windows command prompt?

后端 未结 2 1654
心在旅途
心在旅途 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 22:53

    In section 17.5.3.1. Constants in the subprocess module documentation there's description of subprocess.CREATE_NEW_CONSOLE constant:

    The new process has a new console, instead of inheriting its parent’s console (the default).

    As we see, by default, new process inherits its parent's console. The reason you observe multiple consoles being opened is the fact that you call your scripts from within Eclipse, which itself does not have console so each subprocess creates its own console as there's no console it could inherit. If someone would like to simulate this behavior it's enough to run Python script which creates subprocesses using pythonw.exe instead of python.exe. The difference between the two is that the former does not open a console whereas the latter does.

    The solution is to have helper script — let's call it launcher — which, by default, creates console and runs your programs in subprocesses. This way each program inherits one and the same console from its parent — the launcher. To run programs sequentially we use Popen.wait() method.

    --- script_run_from_eclipse.py ---

    import subprocess
    import sys
    
    subprocess.Popen([sys.executable, 'helper.py'])
    

    --- helper.py ---

    import subprocess
    
    programs = ['first_program.exe', 'second_program.exe']
    for program in programs:
        subprocess.Popen([program]).wait()
        if input('Do you want to continue? (y/n): ').upper() == 'N':
            break
    

提交回复
热议问题