如何保持for循环等待进程结束?

2024-09-29 02:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个简短的python3脚本来多次运行批处理文件(Ctemp.cmd)。脚本如下:

for i in range (START,STOP+1,STEP):
    os.startfile('Ctemp.cmd')

上面的代码几乎同时运行文件。但是,我希望它等到批处理文件完成运行,然后再运行它。在


Tags: 文件代码in脚本cmdforosstep
2条回答

Python3.6.3的答案:

作为per documentation

Run the subprocess module with the .run method. As so:

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None)

Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.

这个答案适用于运行Python2.7的用户:

您可以使用“subprocess”模块和.check_call方法。在

根据the documentation

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.

如英国皇家空军所述:

如果您不关心捕捉错误,您可以只运行.call方法。在

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

Run the command described by args. Wait for command to complete, then return the returncode attribute.

把你的代码改成以下:在

for i in range (START,STOP+1,STEP):
    os.system("Ctemp.cmd")

最好始终为您的cmd文件使用完整路径。如果仍然存在问题,请将Ctemp.cmd文件更改为Ctemp.bat,这样可以解决问题。在

相关问题 更多 >