简体   繁体   中英

Call to several batch files through CMD doesn't block

I'm trying to call several install.bat files one after another with Python trough CMD.

It is necessary that each bat file be displayed in an interactive console window because it asks for some users instructions and that the python program only resume after each CMD process is resolved Each install.bat file can take a pretty long time to finish its process.

My code is the following :

for game in games :
    print("----------- Starting conversion for %s -----------" %game)       
    subprocess.call("start cmd /C " + "Install.bat", cwd=os.path.join(gamesDosDir,game), shell=True)        

print("end")   

But the console windows inside the shell are launched all at once and the "end" message appears event before any of them is finished, whereas I would like them appearing one by one and not go to the n+1 one until the n one is finished and the console window closed (either by user or automatically /K or /C then).

I understand this is some problems using CMD as call should be blocking. How to resolve that? Additionally, if possible how to keep it exactly the same and add 'Y' and 'Y' as default user input?

The most common way to start a batch file (or more generally a CLI command) if to pass it as an argument to cmd /c . After you comment I can assume that you need to use start to force the creation of a (new) command window.

In that case the correct way is to add the /wait option to the start command: it will force the start command to wait the end of its subprocess:

subprocess.call("start /W cmd /C " + "Install.bat", cwd=os.path.join(gamesDosDir,game),
    shell=True)

But @eryksun proposed a far cleaner way. On Windows, .bat files can be executed without shell = True , and creationflags=CREATE_NEW_CONSOLE is enough to ensure a new console is created. So above line could simply become:

subprocess.call("Install.bat", cwd=os.path.join(gamesDosDir,game),
    creationflags = subprocess.CREATE_NEW_CONSOLE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM