我正在使用 subprocess.Popen() 执行命令。我想等待进程完成后再执行其余代码,但同时我想在运行子进程 2 分钟后检查生成的文件的状态。如果文件大小为零,那么我想停止该过程。目前我的代码如下。有没有更聪明的方法来做到这一点?
def execute(command,outputfilename):
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
start_time=time.time()
Is_Working=False
while True:
process.poll()
if not Is_Working:
#allow 2 minutes for the process to create results
if process.returncode == None and (time.time()-start_time)//60>1:
Is_Working=True
if (os.stat(outputfilename)[6]==0):
process.kill()
return
if process.returncode != None:
break
output, errors=process.communicate()
最佳答案
从全局范围来看,你的代码对我来说看起来不错。仅一些细节:
- 在
(time.time()-start_time)//60>1
,我认为//
没有什么用处。 ,因为您不一定需要对结果进行取整,并将除法的 lhs 结果转换为整数。保持全部 float 应该可以进行比较,这都是基本的机器逻辑; - 您可以通过使用
while process.returncode is not None:…
更改循环条件来避免退出无限循环。 - 为了更简单,我实际上会循环直到文件大小为
!=0
然后调用process.wait()
就在循环之后。 - 这将是使用
while/else
的一个很好的场景构造
因此,一项改进是,您可以在流程完成后(无论成功还是失败)执行一些操作(例如清理或重试...):
def execute(command,outputfilename):
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
start_time=time.time()
Is_Working=False
while process.returncode == None:
process.poll()
#allow 2 minutes for the process to create results
if (time.time()-start_time)/60 > 1:
if (os.stat(outputfilename)[6]==0):
process.kill()
break
else:
# the process has not been killed
# wait until it finishes
process.wait()
output, errors=process.communicate()
# do stuff with the output
[…]
# here the process may have been killed or not
[…]
或者另一个好的选择是引发异常:
def execute(command,outputfilename):
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
start_time=time.time()
Is_Working=False
while process.returncode == None:
process.poll()
#allow 2 minutes for the process to create results
if (time.time()-start_time)/60 > 1:
if (os.stat(outputfilename)[6]==0):
process.kill()
raise Exception("Process has failed to do its job")
# the process has not been killed
# wait until it finishes
process.wait()
output, errors=process.communicate()
# do stuff with the output
[…]
HTH
关于python - 运行子进程时检查条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22227569/