[英]How to wait for batch file to end when called from python?
I have a batch file which is zipping a folder as follows(zip.bat):我有一个批处理文件,它正在压缩一个文件夹,如下所示(zip.bat):
for /d %%X in (D:/sample/target/bin) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%X.zip" "%%X\*"
The batch file will zip folder bin and works correctly.批处理文件将压缩文件夹 bin 并正常工作。 Now am calling this batch from a python script as follows:现在我从 python 脚本调用这个批处理,如下所示:
import subprocess as sp
import sys
start_zip_batch = sp.Popen(['D:/zip.bat'],stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, shell = True)
start_zip_batch.wait()
So, now when the script is made to execute it creates the bin.zip folder but keep showing 0 bytes inside it and after a while it stops responding and i need to manually close it.所以,现在当脚本被执行时,它会创建 bin.zip 文件夹,但在其中继续显示 0 字节,一段时间后它停止响应,我需要手动关闭它。 The bin folder is around 403 mb. bin 文件夹大约为 403 mb。 So, please suggest how shall i call zip.bat from python such that it creates te zip folder and then gets closed neatly.所以,请建议我如何从 python 调用 zip.bat 以便它创建 te zip 文件夹,然后整齐地关闭。
There are several subprocess methods that wait for completion.有几个子流程方法等待完成。
check_call
is useful if you want to do cleanup or reporting based on the command return code.如果您想根据命令返回码进行清理或报告,则check_call
很有用。
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) 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.如果返回码为零则返回,否则引发 CalledProcessError。 The CalledProcessError object will have the return code in the returncode attribute. CalledProcessError 对象将在 returncode 属性中包含返回代码。
print('filename')
如果您在.bat
文件中没有任何输出,则可以使用
The easiest and most modern way is to use subprocess.run()
which executes the process and waits for it to complete:最简单和最现代的方法是使用subprocess.run()
来执行进程并等待它完成:
import subprocess
p = subprocess.run(['D:/zip.bat'])
This will execute the process and return a CompletedProcess
object for which you can inspect the returncode
attribute to determine that status.这将执行流程并返回一个CompletedProcess
对象,您可以检查该对象的returncode
属性以确定该状态。
The process's stdout and stderr destinations are unchanged, eg output will still appear on the terminal if the command is run from a terminal.进程的 stdout 和 stderr 目标没有改变,例如,如果命令是从终端运行的,则输出仍会出现在终端上。
You can capture the output of both stdout and stderr if you want:如果需要,您可以捕获 stdout 和 stderr 的输出:
p = subprocess.run(['D:/zip.bat'], capture_output=True)
print(p.stdout.decode())
print(p.stderr.decode())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.