通过 CMD 调用多个批处理文件不会阻塞 [英] Call to several batch files through CMD doesn't block

查看:89
本文介绍了通过 CMD 调用多个批处理文件不会阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 槽 CMD 一个接一个地调用多个 install.bat 文件.

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

有必要在交互式控制台窗口中显示每个 bat 文件,因为它要求一些用户指令,并且 python 程序仅在每个 CMD 进程解决后才恢复每个 install.bat 文件都可能需要很长时间才能完成其进程.

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.

我的代码如下:

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")   

但是外壳内的控制台窗口是一次性启动的,并且结束"消息在其中任何一个完成之前出现事件,而我希望它们一个接一个出现,直到n 完成并关闭控制台窗口(由用户或自动/K 或/C 然后).

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).

我知道这是使用 CMD 的一些问题,因为调用应该被阻塞.如何解决?此外,如果可能,如何保持完全相同并添加Y"和Y"作为默认用户输入?

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?

推荐答案

如果将批处理文件(或更一般的 CLI 命令)作为参数传递给 cmd/c.在您发表评论后,我可以假设您需要使用 start 来强制创建(新)命令窗口.

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.

在这种情况下,正确的方法是在 start 命令中添加 /wait 选项:它将强制 start 命令等待其子进程结束:

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)

但是@eryksun 提出了一种更清洁的方法.在 Windows 上,.bat 文件可以在没有 shell = True 的情况下执行,并且 creationflags=CREATE_NEW_CONSOLE 足以确保创建一个新的控制台.所以上面的行可以简单地变成:

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)

这篇关于通过 CMD 调用多个批处理文件不会阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆